1)抽象工厂模式
JavaScript 的动态性质 排除了描述类的需要接口。
Instead of interfaces, JavaScript trusts that the class you provide implements all the
appropriate methods. At runtime the interpreter will attempt to call the method you
request and, if it is found, call it. The interpreter simply assumes that if your class
implements the method then it is that class. This is known as duck typing.
用冰火里面的国王,国王之手,兰尼斯特家族,塔格里安家族 ,来说明
首先implement一个的King class,这是一个具体的类包含实现的具体细节
let KingJoffery =(function () {
function KingJoffery() {
}
KingJoffery.prototype.makeDecision = function () {
...
};
KingJoffery.prototype.marry = function () {
...
};
return KingJoffery;
})();
implements 一个 HandOfTheKing class
let LordTywin = (function () {
function LordTywin() {
}
LordTywin.prototype.makeDecision = function () {
};
return LordTywin;
})();
具体的工厂类
let LannisterFactory = (function () {
function LannisterFactory() {
}
LannisterFactory.prototype.getKing = function () {
return new KingJoffery();
}
LannisterFactory.prototype.getHandOfTheKing = function () {
return new LordTywin();
};
return LannisterFactory;
})();
上面代码简单地实例化每个所需类的新实例, 并返回它们。
下面是不同的世袭家族的一般形式
let TargaryenFactory = (function () {
function TargaryFactory() {
}
TargaryFactory.prototype.getKing = function () {
return new KingAerys();
}
TargaryFactory.prototype.getHandOfTheKing = function () {
return new LordConnington();
}
return TargaryFactory;
})();
To make use of the Abstract Factory we’ll first need a class that requires the use of
some ruling family
let CourtSession =(function () {
function CourtSession(abstractFactory) {
this.abstractFactory = abstractFactory;
this.COMPLAINT_THRESHOLD = 10;
}
CourtSession.prototype.complaintPresented = function (complaint) {
if (complaint.severity < this.COMPLAINT_THRESHOLD){
this.abstractFactory.getHandOfTheKing().makeDecision();
}else
this.abstractFactory.getKing().makeDecision();
};
return CourtSession;
})();
We can now call this CourtSession class and inject different functionality
depending on which factory we pass in:
let courtSession1 = new CourtSession(new TargaryenFactory());
courtSession1.complaintPresented({ severity : 8});
courtSession1.complaintPresented({ severity: 12});
let courtSession2 = new CourtSession(new LannisterFactory());
courtSession2.complaintPresented({ severity: 8});
courtSession2.complaintPresented({ severity: 12});
It may also be a useful pattern when attempting to ensure that a set of objects be
used together without substitutions