概述
抽象工厂 (abstract factory) 模式又称 Kit 模式,由一个抽象工厂类、多个抽象产品类以及这些抽象类的多个具体子类构成。每个具体工厂类可以创建每个抽象产品类的某个具体子类。
优点:高内聚低耦合,符合“开闭原则”。
缺点:难以添加新的产品类,这涉及到更改抽象工厂类,这个类的修改涉及到其他所有类。
interface ProductA {
show();
}
class ProductA1 implements ProductA {
show() {
//
}
}
class ProductA2 implements ProductA {
show() {
//
}
}
interface ProductB {
use();
}
class ProductB1 implements ProductB {
use() {
//
}
}
class ProductB2 implements ProductB {
use() {
//
}
}
interface Factory {
ProductA createA();
ProductB createB();
}
class Factory1 implements Factory {
public static ProductA createA() {
return new ProductA1();
}
public static ProductB createB() {
return new ProductB1();
}
}
class Factory2 implements Factory {
public static ProductA createA() {
return new ProductA2();
}
public static ProductB createB() {
return new ProductB2();
}
}
public class Test {
public static void main(String[] args) {
Factory f;
ProductA pa;
ProductB pb;
f = new Factory1(); // or get from some file
pa = f.createA();
pb = f.createB();
pa.show();
pb.use();
}
}
图示
参考
[1] 刘伟,设计模式,2011.
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix