抽象工厂模式

  • 提供一个创建一系列的相关或相互依赖对象的接口,而无需指定他们具体的类
    Abstract Factory
  • 这就是那个”抽象工厂”,一个手机工厂,创建耳机和屏幕
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
public interface PhoneFactory {
EarPhone createEarPhone();
Screen createScreen();
}
public class AppleFactory implements PhoneFactory{
@Override public EarPhone createEarPhone() {
return new LightingPointEar();
}
@Override public Screen createScreen() {
return new FourPointSevenScreen();
}
}
public class SamsungFactory implements PhoneFactory {
@Override public EarPhone createEarPhone() {
return new ThreePointFiveEar();
}
@Override public Screen createScreen() {
return new FivePointFiveScreen();
}
}
  • 相关的产品类
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
/**
* 屏幕接口
*/
public interface Screen {
float size();
}
public class FivePointFiveScreen implements Screen {
//5.5寸
@Override public float size() {
return 5.5F;
}
}
public class FourPointSevenScreen implements Screen {
//4.7寸
@Override public float size() {
return 4.7F;
}
}
/**
* 耳机接口
*/
public interface EarPhone {
String showInterfaceType();
}
public class LightingPointEar implements EarPhone {
@Override public String showInterfaceType() {
return "Lighting接口的耳机";
}
}
public class ThreePointFiveEar implements EarPhone {
@Override public String showInterfaceType() {
return "3.5mm接口的耳机";
}
}
  • 客户端
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public class App {
public static void main(String[] args) {
// 抽象工厂模式:提供一个一系列相关或者相互依赖对象的接口,而无需指定他们具体的类
// 比如此例中,苹果手机的工厂返回的耳机与屏幕是相关的lighting与4.7寸
// 增加具体产品工厂较为容易,如XiaomiFactory,而增加一个相关产品较为难,比如增加手机的摄像头这个产品,需要改很多类
PhoneFactory apple=new AppleFactory();
System.out.println(apple.createEarPhone().showInterfaceType());
System.out.println(apple.createScreen().size());
PhoneFactory samsung=new SamsungFactory();
System.out.println(samsung.createEarPhone().showInterfaceType());
System.out.println(samsung.createScreen().size());
}
}

原型模式

  • 用原型实例指定创建对象的种类,并且通过拷贝这些原型创建新的对象
    Prototype
  • 原型的接口与自定义的原型
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
/**
* 手机原型接口
*/
interface PhonePrototype {
PhonePrototype clone();
String getName();
void setName(String name);
String getCpu();
void setCpu(String cpu);
String getGpu();
void setGpu(String gpu);
String getColor();
void setColor(String color);
String getFlashMemory();
void setFlashMemory(String flashMemory);
String getCamera();
void setCamera(String camera);
}
/**
* 自定义的原型IPhone原型
*/
public class IphonePrototype implements PhonePrototype,Serializable {
private String cpu;
private String gpu;
private String color;
private String flashMemory;
private String camera;
private String name;
public IphonePrototype() {
}
public String getCpu() {
return cpu;
}
public void setCpu(String cpu) {
this.cpu = cpu;
}
public String getGpu() {
return gpu;
}
public void setGpu(String gpu) {
this.gpu = gpu;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public String getFlashMemory() {
return flashMemory;
}
public void setFlashMemory(String flashMemory) {
this.flashMemory = flashMemory;
}
public String getCamera() {
return camera;
}
public void setCamera(String camera) {
this.camera = camera;
}
@Override
public PhonePrototype clone() {
return (PhonePrototype)ClassUtil.deepCopy(this);
}
@Override
public String getName() {
return name;
}
@Override
public void setName(String name) {
this.name=name;
}
}
  • 创建一个原型管理器用于统一管理所有的原型
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
/**
* Created with IntelliJ IDEA. User: pingansheng Date: 2016/11/12 Time: 11:19
*/
public class PrototypeManager {
/**
* 用来记录原型的编号和原型实例的对应关系
*/
private static Map<String,PhonePrototype> map = new HashMap<>();
/**
* 私有化构造方法,避免外部创建实例
*/
private PrototypeManager(){}
/**
* 向原型管理器里面添加或是修改某个原型注册
* @param prototypeId 原型编号
* @param prototype 原型实例
*/
public synchronized static void setPrototype(String prototypeId , PhonePrototype prototype){
map.put(prototypeId, prototype);
}
/**
* 从原型管理器里面删除某个原型注册
* @param prototypeId 原型编号
*/
public synchronized static void removePrototype(String prototypeId){
map.remove(prototypeId);
}
/**
* 获取某个原型编号对应的原型实例
* @param prototypeId 原型编号
* @return 原型编号对应的原型实例
* @throws Exception 如果原型编号对应的实例不存在,则抛出异常
*/
public synchronized static PhonePrototype getPrototype(String prototypeId) throws Exception{
PhonePrototype prototype = map.get(prototypeId);
if(prototype == null){
throw new Exception("您希望获取的原型还没有注册或已被销毁");
}
return prototype;
}
}
  • 客户端对原型的使用
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
public class App {
/**
* 原型模式,根据一个给定的对象创建新的对象,即克隆,一般使用深度复制
* @param args
*/
public static void main(String[] args) throws Exception{
//创建模型,一般使用此模式,表示此对象难以构造或后续使用需要修改的属性等信息较少
PhonePrototype iphonePrototype=new IphonePrototype();
iphonePrototype.setCpu("A8");
iphonePrototype.setGpu("A8");
iphonePrototype.setCamera("Single 1200M");
//放入模型管理器统一管理
PrototypeManager.setPrototype("iphoneModel",iphonePrototype);
//客户端使用原型构造各自的对象
PhonePrototype model=PrototypeManager.getPrototype("iphoneModel");
PhonePrototype iphone64G=model.clone();
iphone64G.setColor("black");
iphone64G.setFlashMemory("64G");
PhonePrototype iphone128G=model.clone();
iphone128G.setColor("golden");
iphone128G.setFlashMemory("128G");
System.out.println(JSON.toJSONString(iphone64G));
System.out.println(JSON.toJSONString(iphone128G));
}
}
  • 一个深度复制的方案
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
/**
* 深度复制 需要对象及相关对象实现串行化接口
*
* @param obj
* @return
* @throws Exception
*/
public static Serializable deepCopy(Serializable obj) {
ByteArrayOutputStream bos = null;
ObjectOutputStream oos = null;
ByteArrayInputStream bis = null;
ObjectInputStream ois = null;
Serializable target = null;
try {
bos = new ByteArrayOutputStream();
oos = new ObjectOutputStream(bos);
oos.writeObject(obj);
byte[] bytes = bos.toByteArray();
bis = new ByteArrayInputStream(bytes);
ois = new ObjectInputStream(bis);
target = (Serializable) ois.readObject();
oos.close();
bos.close();
ois.close();
bis.close();
return target;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}

构造器模式

  • 将一个复杂对象的构建与它的表示分离,使同样的构建过程可以创建不同的表示
    Builder
  • 构造器的使用者,构建过程的持有方(算法)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
public interface Director {
void constuct(PhoneBuilder builder);
}
//制作一个手机
public class PhoneDirector implements Director {
public void constuct(PhoneBuilder builder){
builder.buildCamera();
builder.buildEarphone();
builder.buildScreen();
}
}
//打包两个手机
public class PhoneBoxDirector implements Director {
@Override public void constuct(PhoneBuilder builder) {
builder.buildCamera();
builder.buildCamera();
builder.buildEarphone();
builder.buildEarphone();
builder.buildScreen();
builder.buildScreen();
}
}
  • 手机构造器builder
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
public interface PhoneBuilder {
void buildScreen();
void buildEarphone();
void buildCamera();
String getResult();
}
public class ApplePhoneBuilder implements PhoneBuilder {
private int screenCount;
private int earPhoneCount;
private int cameraCount;
@Override public void buildScreen() {
System.out.println("构建苹果屏幕");
screenCount++;
}
@Override public void buildEarphone() {
System.out.println("构建苹果耳机");
earPhoneCount++;
}
@Override public void buildCamera() {
System.out.println("构建苹果摄像头");
cameraCount++;
}
@Override public String getResult() {
return "苹果手机构建完成,组件数量:"+screenCount+" "+earPhoneCount+" "+cameraCount;
}
}
public class SamsungPhoneBuilder implements PhoneBuilder {
private int screenCount;
private int earPhoneCount;
private int cameraCount;
@Override public void buildScreen() {
System.out.println("构建三星屏幕");
screenCount++;
}
@Override public void buildEarphone() {
System.out.println("构建三星耳机");
earPhoneCount++;
}
@Override public void buildCamera() {
System.out.println("构建三星摄像头");
cameraCount++;
}
@Override public String getResult() {
return "三星手机构建完成,组件数量:" + screenCount + " " + earPhoneCount + " " + cameraCount;
}
}
  • 客户端
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
public class App {
/**
* 构建器模式,将对象的构建(对象的构造顺序或策略)与表示分离
* @param args
*/
public static void main(String[] args) {
PhoneBuilder appleBuilder=new ApplePhoneBuilder();
PhoneBuilder samsungPhoneBuilder=new SamsungPhoneBuilder();
PhoneBuilder[] builders={appleBuilder,samsungPhoneBuilder};
//第一种构建的策略
Director direct1=new PhoneDirector();
for(int i=0;i<builders.length;i++){
direct1.constuct(builders[i]);//这里是构建的方法,而不存储构建的结果
System.out.println(builders[i].getResult());//构建的结果由具体的构造器返回
}
//第二种构建的策略
Director direct2=new PhoneBoxDirector();
for(int i=0;i<builders.length;i++){
direct2.constuct(builders[i]);//这里是构建的方法,而不存储构建的结果
System.out.println(builders[i].getResult());//构建的结果由具体的构造器返回
}
}
}