一天一个设计模式(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

原文地址:https://www.cnblogs.com/Bin-x/p/design2.html