設計模式-建立型模式-工廠模式(工廠三兄弟) TypeScript
簡單工廠模式
定義一個介面,三個具體類。然後書寫如下,通過選擇,生產出相應的物件
// 定義Shape介面
interface Shape {
draw():void;
}
// 下面為產品類
// 產品 Circle
class Circle implements Shape{
public constructor(){
}
public draw():void{
}
}
// 產品Rectangle
class Rectangle implements Shape{
public constructor(){
}
public draw():void{
}
}
// 下面為生產產品的工廠,根據選擇,生產出不同的產品
class ShapeFactory {
constructor(){
}
public static getShape(typeShape:string):Shape{
if(typeShape === "Circle"){
return new Circle();
}
if (typeShape === "Rectangle"){
return new Rectangle();
}
if (typeShape === null){
return null;
}
return null;
}
}
// 下面編寫測試
let test:Shape = ShapeFactory.getShape("Circle");
// 呼叫draw方法
test.draw();
複製程式碼
編譯後的js如下
// 下面為產品類
// 產品 Circle
var Circle = /** @class */ (function () {
function Circle() {
}
Circle.prototype.draw = function () {
};
return Circle;
}());
// 產品Rectangle
var Rectangle = /** @class */ (function () {
function Rectangle() {
}
Rectangle.prototype.draw = function () {
};
return Rectangle;
}());
// 下面為生產產品的工廠,根據選擇,生產出不同的產品
var ShapeFactory = /** @class */ (function () {
function ShapeFactory() {
}
ShapeFactory.getShape = function (typeShape) {
if (typeShape === "Circle") {
return new Circle();
}
if (typeShape === "Rectangle") {
return new Rectangle();
}
if (typeShape === null) {
return null;
}
return null;
};
return ShapeFactory;
}());
// 下面編寫測試
var test = ShapeFactory.getShape("Circle");
// 呼叫draw方法
test.draw();
複製程式碼
利用反射改進
class ShapeFactory1 {
constructor(){
};
public static getShape<T extends Shape>(c:{new ():T}):T{ // C型別為類
return new c();
}
}
let test = ShapeFactory1.getShape(Circle);
test.draw();
複製程式碼
var ShapeFactory1 = /** @class */ (function () {
function ShapeFactory1() {
}
;
ShapeFactory1.getShape = function (c) {
return new c();
};
return ShapeFactory1;
}());
var test = ShapeFactory1.getShape(Circle);
test.draw();
複製程式碼
工廠方法
即,將工廠拆分
// 工廠方法
class CircleFactory{
constructor(){
}
public static getShape():Shape{
return new Circle();
}
}
class RectangleFactory{
constructor(){
}
public static getShape():Shape{
return new Rectangle();
}
}
let test = CircleFactory.getShape();
test.draw();
複製程式碼
抽象工廠
抽象工廠比較簡單不在闡述。