一天一个设计模式(2)——抽象工厂模式
抽象工厂模式
与工厂模式类似,抽象工厂模式旨在解决多级结构的解耦问题。工厂模式解决了类选择的问题,而抽象工厂模式解决了接口选择的问题。
举个例子,我要画一个图形,图形可以是方的,圆的,同样,图形有颜色,红色或者蓝色。那么我们有4种选择,红色的方形,红色的圆形,蓝色的方形和蓝色的圆形。
很显然,工厂模式满足不了我们的要求,这个时候就要抽象工厂模式出厂了。
图例如下:
好吧,图画的有点渣,不过应该还是容易看懂的。
代码示例

1 /** 2 *首先是两个接口 3 */ 4 public interface Color { 5 void fill(); 6 } 7 public interface Shape { 8 void draw(); 9 } 10 /** 11 *具体的实现类 12 */ 13 public class Circle implements Shape { 14 public void draw(){ 15 System.out.println("draw circle"); 16 } 17 } 18 public class Square implements Shape { 19 public void draw(){ 20 System.out.println("draw square"); 21 } 22 } 23 24 public class Red implements Color { 25 public void fill(){ 26 System.out.println("color is red"); 27 } 28 } 29 public class Blue implements Color { 30 public void fill(){ 31 System.out.println("color is blue"); 32 } 33 } 34 35 /** 36 *抽象工厂 37 */ 38 public interface AbstractFactory { 39 Color getColor(String color); 40 Shape getShape(String shape); 41 } 42 43 /** 44 *实现抽象工厂 45 */ 46 public class Factory implements AbstractFactory { 47 48 @Override 49 public Shape getShape(String shape) { 50 if (shape.equalsIgnoreCase("circle")) 51 return new Circle(); 52 if (shape.equalsIgnoreCase("square")) 53 return new Square(); 54 return null; 55 } 56 57 @Override 58 public Color getColor(String color) { 59 if (color.equalsIgnoreCase("red")) 60 return new Red(); 61 if (color.equalsIgnoreCase("blue")) 62 return new Blue(); 63 return null; 64 } 65 } 66 67 /** 68 *执行 69 */ 70 public class Main { 71 public static void main(String[] args) { 72 AbstractFactory Factory = new Factory(); 73 Shape shape = Factory.getShape("circle"); 74 shape.draw(); 75 Color color = Factory.getColor("red"); 76 color.fill(); 77 } 78 }
本文来自博客园,作者:Bin_x,转载请注明原文链接:https://www.cnblogs.com/Bin-x/p/design2.html
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)