抽象工厂模式

抽象工厂模式(Abstract Factory Pattern)是围绕一个超级工厂创建其他工厂。该超级工厂又称为其他工厂的工厂。这种类型的设计模式属于创建型模式,它提供了一种创建对象的最佳方式。

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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155

/*
* Copyright,ShanNong Inc,2018 and onwards
*
* Author:fanghua fan
*/

package com.fanghua.designpattrn.abstractfactory;

public class AbstractFactoryPattern {
public static void main(String[] args) {
AbstractFactory sf = FactoryProducer.getFactory(FactoryType.ARTS_FACTORY);

LiberalArts asf = sf.getArts(LiberalArtsType.HISTORY);

asf.artsContent();
}
}

/**
* 理科
*/
interface Science {
void scienceContent();
}

/**
* 文科
*/
interface LiberalArts {
void artsContent();
}

/**
* 数学分析
*/
class AnalysicsMath implements Science {
public void scienceContent() {
System.out.println("greate math!");
}
}

/**
* 理论物理学
*/
class TheoreticalPhysics implements Science {
public void scienceContent() {
System.out.println("greate physics!");
}
}

/**
* 历史学
*/
class History implements LiberalArts {
public void artsContent() {
System.out.println("beautiful history!");
}
}

/**
* 政治学
*/
class Politics implements LiberalArts {
public void artsContent() {
System.out.println("beautiful politics!");
}
}


/**
* 抽象工厂
*/
abstract class AbstractFactory {
abstract Science getScience(ScienceType name);

abstract LiberalArts getArts(LiberalArtsType name);
}

/**
* 理科工厂
*/
class ScienceFactory extends AbstractFactory {
Science getScience(ScienceType name) {
switch (name) {
case MATH:
return new AnalysicsMath();
case PHYSICS:
return new TheoreticalPhysics();
}
return null;
}

LiberalArts getArts(LiberalArtsType name) {
return null;
}
}

/**
* 文科工厂
*/
class LiberalArtsFactory extends AbstractFactory {
Science getScience(ScienceType name) {
return null;
}

LiberalArts getArts(LiberalArtsType name) {
switch (name) {
case HISTORY:
return new History();
case POLITICS:
return new Politics();
}
return null;
}
}

/**
* 理科对象类型枚举
*/
enum ScienceType {
MATH,
PHYSICS
}

/**
* 文科对象类型枚举
*/
enum LiberalArtsType {
HISTORY,
POLITICS
}

/**
* 工厂类型
*/
enum FactoryType {
SCIENCE_FACTORY,
ARTS_FACTORY
}

/**
* 工厂对象提供者
*/
class FactoryProducer {
public static AbstractFactory getFactory(FactoryType choice) {
switch (choice) {
case SCIENCE_FACTORY:
return new ScienceFactory();
case ARTS_FACTORY:
return new LiberalArtsFactory();
}
return null;
}
}

(全文完)4/2/2018 9:09:08 PM