抽象工厂模式Abstract Factory是通过对类的工厂抽象使其业务用于对产品类簇的创建,而不仅仅是负责创建某一类产品的实例,抽象工厂模式提供一个创建一系列相关或相互依赖对象的接口,而无须指定它们具体的类,抽象工厂模式又称为Kit模式,属于对象创建型模式。
在工厂方法模式中具体工厂负责生产具体的产品,每一个具体工厂对应一种具体产品,工厂方法也具有唯一性,一般情况下一个具体工厂中只有一个工厂方法或者一组重载的工厂方法,但是有时候我们需要一个工厂可以提供多个产品对象,而不是单一的产品对象,当系统所提供的工厂所需生产的具体产品并不是一个简单的对象,而是多个位于不同产品等级结构中属于不同类型的具体产品时需要使用抽象工厂模式。 抽象工厂模式与工厂方法模式最大的区别在于,工厂方法模式针对的是一个产品等级结构,而抽象工厂模式则需要面对多个产品等级结构,一个工厂等级结构可以负责多个不同产品等级结构中的产品对象的创建 。当一个工厂等级结构可以创建出分属于不同产品等级结构的一个产品族中的所有对象时,抽象工厂模式比工厂方法模式更为简单、有效率。
AbstractFactory: 抽象工厂。ConcreteFactory: 具体工厂。AbstractProduct: 抽象产品。Product: 具体产品。class Shape { // 形状基类
draw(){
console.log(this.shape);
}
}
class Rectangle extends Shape{ // 长方形
constructor(){
super();
this.shape = "Rectangle";
}
}
class Square extends Shape{ // 正方形
constructor(){
super();
this.shape = "Square";
}
}
class Circle extends Shape{ // 圆形
constructor(){
super();
this.shape = "Circle";
}
}
class Color { // 颜色基类
fill(){
console.log(this.color);
}
}
class Red extends Color{ // 红色
constructor(){
super();
this.color = "Red";
}
}
class Green extends Color{ // 绿色
constructor(){
super();
this.color = "Green";
}
}
class Blue extends Color{ // 蓝色
constructor(){
super();
this.color = "Blue";
}
}
class Factory{ // 工厂基类 模拟抽象方法
getShape(){
throw new Error("Abstract method cannot be called");
}
getColor(){
throw new Error("Abstract method cannot be called");
}
}
class ShapeFactory extends Factory{ // 形状工厂
getShape(shape){
switch (shape.toLowerCase()) {
case "rectangle":
return new Rectangle();
case "square":
return new Square();
case "circle":
return new Circle();
default:
throw new Error("参数错误");
}
}
getColor(){
return null;
}
}
class ColorFactory extends Factory{ // 颜色工厂
getShape(){
return null;
}
getColor(color){
switch (color.toLowerCase()) {
case "red":
return new Red();
case "green":
return new Green();
case "blue":
return new Blue();
default:
throw new Error("参数错误");
}
}
}
class FactoryGenerator{ // 工厂生成器类 通过传递形状或颜色来获取工厂
static getFactory(choice){
choice = choice.toLowerCase();
if(choice === "shape") {
return new ShapeFactory();
}else if(choice === "color"){
return new ColorFactory();
}
throw new Error("参数错误");
}
}
(function(){
var shapeFactory = FactoryGenerator.getFactory("shape");
var colorFactory = FactoryGenerator.getFactory("color");
shapeFactory.getShape("rectangle").draw();
shapeFactory.getShape("square").draw();
shapeFactory.getShape("circle").draw();
colorFactory.getColor("red").fill();
colorFactory.getColor("green").fill();
colorFactory.getColor("blue").fill();
})();https://github.com/WindrunnerMax/EveryDayhttps://www.runoob.com/design-pattern/abstract-factory-pattern.html
https://wiki.jikexueyuan.com/project/java-design-pattern/abstract-factory-pattern.html
https://design-patterns.readthedocs.io/zh_CN/latest/creational_patterns/abstract_factory.html