1. 程式人生 > 其它 >SSRF 服務端請求偽造 漏洞

SSRF 服務端請求偽造 漏洞

什麼是模板模式

模板方法模式是一種只需使用繼承就可以實現的非常簡單的模式。
模板方法模式由兩部分結構組成,第一部分是抽象父類,第二部分是具體的實現子類。通常在抽象父類中封裝了子類的演算法框架,包括實現一些公共方法以及封裝子類中所有方法的執行順序。子類通過繼承這個抽象類,也繼承了整個演算法結構,並且可以選擇重寫父類的方法。

模板模式例子: 傻強,嚯茶還是coffee

泡咖啡的步驟:

(1) 把水煮沸
(2) 用沸水沖泡咖啡
(3) 把咖啡倒進杯子
(4) 加糖和牛奶

var Coffee = function(){};
Coffee.prototype.boilWater = function(){
 console.log( '把水煮沸' );
};
Coffee.prototype.brewCoffeeGriends = function(){
 console.log( '用沸水沖泡咖啡' );
};
Coffee.prototype.pourInCup = function(){
 console.log( '把咖啡倒進杯子' );
};
Coffee.prototype.addSugarAndMilk = function(){
 console.log( '加糖和牛奶' );
};
Coffee.prototype.init = function(){
 this.boilWater();
 this.brewCoffeeGriends();
 this.pourInCup();
 this.addSugarAndMilk();
};
var coffee = new Coffee();
coffee.init(); 

泡茶的步驟:

(1) 把水煮沸
(2) 用沸水浸泡茶葉
(3) 把茶水倒進杯子
(4) 加檸檬

var Tea = function(){};
Tea.prototype.boilWater = function(){
 console.log( '把水煮沸' );
};
Tea.prototype.steepTeaBag = function(){
 console.log( '用沸水浸泡茶葉' );
};
Tea.prototype.pourInCup = function(){
 console.log( '把茶水倒進杯子' );
};
Tea.prototype.addLemon = function(){
 console.log( '加檸檬' );
};
Tea.prototype.init = function(){
 this.boilWater();
 this.steepTeaBag();
 this.pourInCup();
 this.addLemon();
};
var tea = new Tea();
tea.init(); 

分離公共的點


經過抽象之後,不管是泡咖啡還是泡茶,我們都能整理為下面四步:

(1) 把水煮沸
(2) 用沸水沖泡飲料
(3) 把飲料倒進杯子
(4) 加調料

var Beverage = function(){};
Beverage.prototype.boilWater = function(){
 console.log( '把水煮沸' );
};
Beverage.prototype.brew = function(){}; // 空方法,應該由子類重寫
Beverage.prototype.pourInCup = function(){}; // 空方法,應該由子類重寫
Beverage.prototype.addCondiments = function(){}; // 空方法,應該由子類重寫
Beverage.prototype.init = function(){
 this.boilWater();
 this.brew();
 this.pourInCup();
 this.addCondiments();
}; 

建立 Coffee 子類和 Tea 子類

var Coffee = function(){};
Coffee.prototype = new Beverage();
Coffee.prototype.brew = function(){
 console.log( '用沸水沖泡咖啡' );
};
Coffee.prototype.pourInCup = function(){
 console.log( '把咖啡倒進杯子' ); 
};
Coffee.prototype.addCondiments = function(){
 console.log( '加糖和牛奶' );
};
var Coffee = new Coffee();
Coffee.init();
// 泡茶
var Tea = function(){};
Tea.prototype = new Beverage();
Tea.prototype.brew = function(){
 console.log( '用沸水浸泡茶葉' );
};
Tea.prototype.pourInCup = function(){
 console.log( '把茶倒進杯子' );
};
Tea.prototype.addCondiments = function(){
 console.log( '加檸檬' );
};
var tea = new Tea();
tea.init(); 

小結

模板方法模式是一種典型的通過封裝變化提高系統擴充套件性的設計模式。在傳統的面嚮物件語言中,一個運用了模板方法模式的程式中,子類的方法種類和執行順序都是不變的,所以我們把這部分邏輯抽象到父類的模板方法裡面。而子類的方法具體怎麼實現則是可變的,於是我們把這部分變化的邏輯封裝到子類中。通過增加新的子類,我們便能給系統增加新的功能,並不需要改動抽象父類以及其他子類,這也是符合開放封閉原則的。但在 JavaScript 中,我們很多時候都不需要依樣畫瓢地去實現一個模版方法模式,高階函式是更好的選擇。