设计模式总结

创建型模式

1. 抽象工厂

模式名称:抽象工厂

意图:提供一个创建一系列相关或相互依赖对象的接口,而无需制定他们具体的类。

应用场景:

(1)系统独立于它的创建、组合和表示。

(2)一个系统要由多个产品系列中的一个来配置的。

(3)当强调一系列相关的产品对象的设计以便联合使用。

(4)若提供类库,只想提供接口,而不是实现。

java例子:

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
// 抽象工厂接口:
public interface AbstractFactory {
public Shoes GreateShoes(); // 生产鞋子
public Hat GreateHat(); // 生产帽子
}
//实例工厂1:
public class Factory1 implements AbstractFactory {
@Override
public Shoes GreateShoes() { //工厂1创建运动鞋
System.out.print("工厂1");
return new SportShoes();
}
@Override
public Hat GreateHat() { //工厂1创建红帽子
System.out.print("工厂1");
return new RedHat();
}

}
//实例工厂2:
public class Factory2 implements AbstractFactory {
@Override
public Shoes GreateShoes() {
System.out.print("工厂2");
return new CasualShoes(); //工厂2创建休闲鞋
}
@Override
public Hat GreateHat() {
System.out.print("工厂2");
return new WhiteHat(); //工厂2创建白帽子
}
}
//帽子类型接口:
public interface Hat { }
//帽子的实现类红帽子:
public class RedHat implements Hat {
RedHat(){
System.out.println("创建红帽子");
}
}
//帽子的实现类白帽子:
public class WhiteHat implements Hat {
WhiteHat(){
System.out.println("创建白帽子");
}
}
//鞋子类型接口
public interface Shoes { }
//鞋子的实现类运动鞋
public class SportShoes implements Shoes {
SportShoes(){
System.out.println("创建运动鞋");
}
}
//鞋子的实现类休闲鞋
public class CasualShoes implements Shoes {
CasualShoes(){
System.out.println("创建休闲鞋");
}
}
//客户端
public class Client {
public static void main(String[] args) {
Shoes shoes = new Factory1().GreateShoes();
Shoes shoes1 = new Factory2().GreateShoes();
Hat hat1 = new Factory1().GreateHat();
Hat hat2 = new Factory2().GreateHat();
}
}

2. 生成器

模式名称:生成器模式    别名:建造模式

模式意图:将一个复杂对象的构建与它的表示分离,使得同样的构建过程可以创建不同的表示。

应用场景:

(1)当创建复杂对象的算法应该独立于与该对象的组成部分以及他们的装配方式时。

(2)当构造过程必须被构造的对象有不同的表示时。

java例子:

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
//基类:
class Computer {
private String Screen; //显示屏幕
private String Mouse; //鼠标
private String KeyBoard; //键盘
public void setScreen(String screen) {
Screen = screen;
}
public void setMouse(String mouse) {
Mouse = mouse;
}
public void setKeyBoard(String keyBoard) {
KeyBoard = keyBoard;
}
public String toString() {
return "Computer [Screen=" + Screen + ", Mouse=" + Mouse+ ", KeyBoard=" + KeyBoard + "]";
}
}
//创建电脑的类
public abstract class ComputerBuilder {
protected Computer computer;
public Computer getComputer(){ return computer; }
public void createNewComputer(){ computer = new Computer();}
public abstract void buildScreen();
public abstract void buildMouse();
public abstract void buildKeyBoard();
}
//实现类 联想电脑
class LenovoComputer extends ComputerBuilder {
public void buildScreen() {computer.setScreen("lenovo screen");}
public void buildMouse() {computer.setMouse("lenovo mouse");}
public void buildKeyBoard() {computer.setKeyBoard("lenovo keyBoard");}
}
//实现类 戴尔电脑
class DellComputer extends ComputerBuilder{
public void buildScreen() {computer.setScreen("dell screen");}
public void buildMouse() {computer.setMouse("dell mouse");}
public void buildKeyBoard() {computer.setKeyBoard("dell keyBoard");}
}
//售货员类
public class Assisstant {
private ComputerBuilder cb; //传入一个电脑的厂家
public Computer getComputer(){return cb.getComputer();}
public void setComputerBuilder(ComputerBuilder cb){this.cb = cb;}
public void createNewComputer(){
cb.createNewComputer(); //创建新的电脑
cb.buildKeyBoard(); //创建键盘
cb.buildMouse(); //创建鼠标
cb.buildScreen(); //创建显示器
}
}
//客户端
public class Client {
public static void main(String[] args) {
Assisstant as = new Assisstant();
ComputerBuilder lenovo = new LenovoComputer();
ComputerBuilder deel = new DellComputer();
as.setComputerBuilder(lenovo);
as.createNewComputer();
Computer computer = as.getComputer();
System.out.println(computer);
as.setComputerBuilder(deel);
as.createNewComputer();
Computer computer1 = as.getComputer();
System.out.println(computer1);
}
}

3. 原型

模式名称 : 原型模式

意图:用原型实例制定创建对象的种类,并且通过拷贝这些原型创建新的对象。

应用场景:


(1)当要实例化的类是在运行时刻制定时,例如,通过动态装载。

(2)为了避免创建一个与产品层次平行的工厂类层次时。

(3)当一个类的实例只能有几个不同状态组合中的一种时。

java例子:

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
//原型接口
public interface Prototype {
public Object cloneMe() throws CloneNotSupportedException;
}
//通过克隆得到对象
public class Cublic implements Prototype, Cloneable {
public Object cloneMe() throws CloneNotSupportedException {
return (Cublic)clone();
}
public String toString() {return "Cublic []";}
}
//通过序列化得到对象
public class Goat implements Prototype, Serializable {
public String toString() {return "Goat []";}
public Object cloneMe() throws CloneNotSupportedException {
Object obj = null;
try {
ByteArrayOutputStream outOne = new ByteArrayOutputStream();
ObjectOutputStream outTwo = new ObjectOutputStream(outOne);
outTwo.writeObject(this);
ByteArrayInputStream inOne = new ByteArrayInputStream(outOne.toByteArray());
ObjectInputStream inTwo = new ObjectInputStream(inOne);
obj = inTwo.readObject();
} catch (Exception e) {
e.printStackTrace();
}
return obj;
}
}
//客户端
public class Client {
public static void main(String[] args) throws CloneNotSupportedException {
Goat goat = new Goat();
System.out.println("通过对象流得到:"+goat.cloneMe());
Cublic cb = new Cublic();
System.out.println("通过拷贝得到:"+cb.cloneMe());
}
}

结构型模式

1. 适配器模式

模式名称:适配器模式   别名:包装器

意图:将一个类的接口转换成客户希望的另一个接口。

应用场景:

(1)想要使用某个已经存在的类,而它的接口不符合需求。

(2)想要创建一个可复用的类,该类可以和其他部相关的类或不可预见的类协同工作。

(3)想要使用一些已经存在的子类,但是不可能对每一个都进行子类化以匹配他们的接口。对象的适配器可以适配它父类的接口。

java例子:

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
//三孔插座接口
public interface ThreeSocketInf {
public void powerWithThreeSocket();
}
//三孔插座实现
public class ThreeSocket implements ThreeSocketInf {
public void powerWithThreeSocket() {
System.out.print("使用三孔插座充电");
}
}
//两孔插座接口
public interface TwoSocketInf {
public void powerWithTwoSocket();
}
//两孔插座实现
public class TwoSocket implements TwoSocketInf {
public void powerWithTwoSocket() {
System.out.println("使用两孔插座充电");
}
}
//适配器
public class SocketAdapter implements TwoSocketInf {
private ThreeSocketInf ts;
public SocketAdapter(ThreeSocketInf ts) {
this.ts = ts;
}
@Override
public void powerWithTwoSocket() {
ts.powerWithThreeSocket();
System.out.print("---> 适配为两口");
}
}
//客户端
public class Client {
public static void main(String[] args) {
ThreeSocketInf three = new ThreeSocket();
SocketAdapter sa = new SocketAdapter(three);
sa.powerWithTwoSocket();
}
}

2. 适配器模式

模式名称:桥接模式

意图:将抽象部分与实现部分分离,使它们都可以独立的变化。

应用场景:(1)如果一个系统需要在构件的抽象化角色和具体化角色之间增加更多的灵活性,避免在两个层次之间建立静态的联系。

(2)设计要求实现化角色的任何改变不应当影响客户端,或者说实现化角色的改变对客户端是完全透明的。

(3)一个构件有多于一个的抽象化角色和实现化角色,系统需要它们之间进行动态耦合。

(4).虽然在系统中使用继承是没有问题的,但是由于抽象化角色和具体化角色需要独立变化,设计要求需要独立管理这两者。

UML类图:



java例子:

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
//抽象车
public class AbstractCar {
void run(){ System.out.println("车");}
}
//实例公交车
public class Bus extends AbstractCar {
void run(){ System.out.print("公交车");}
}
//实例小轿车
public class Car extends AbstractCar {
void run(){ System.out.print("小轿车");}
}
//抽象路
public class Road {
AbstractCar car;
public void run(){ System.out.println("道路"); }
}
//实例街道路
public class StreetRode extends Road {
public void run(){
car.run();
System.out.println("在街区路行驶");
}
}
//实例高速路
public class SpeedWay extends Road {
public void run(){
car.run();
System.out.print("在高速路行驶");
}
}
//客户端
public class Client {
public static void main(String[] args) {
Road road =new SpeedWay();
road.car = new Car();
road.run();
System.out.println();
Road road1 =new StreetRode();
road1.car = new Bus();
road1.run();
}
}

3.代理模式

模式名称:代理模式

意图:为其他对象提供一种代理以控制对这个对象的访问。

应用场景:(1)远程代理(Remote Proxy) -可以隐藏一个对象存在于不同地址空间的事实。也使得客户端可以访问在远程机器上的对象,远程机器可能具有更好的计算性能与处理速度,可以快速响应并处理客户端请求。

(2)虚拟代理(Virtual Proxy) – 允许内存开销较大的对象在需要的时候创建。只有我们真正需要这个对象的时候才创建。

(3)写入时复制代理(Copy-On-Write Proxy) – 用来控制对象的复制,方法是延迟对象的复制,直到客户真的需要为止。是虚拟代理的一个变体。

(4)保护代理(Protection (Access)Proxy) – 为不同的客户提供不同级别的目标对象访问权限。

java例子:

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
//抽象对象
public abstract class Subject {
abstract public void request();
}
//真实对象
public class RealSubject extends Subject {
public void request() {System.out.println("真实对象处理请求");}
}
//代理与相同对象继承相同的类
public class ProxySubject extends Subject {
private RealSubject rs; //持有真实对象的引用
@Override
public void request() {
if(rs == null ) rs = new RealSubject();
System.out.print("通过代理 ");
rs.request();
}
}
//客户端通过代理来调用真实对象
public class Client {
public static void main(String[] args) {
ProxySubject ps = new ProxySubject();
ps.request();
}
}

行为型模式

1.命令模式

模式名称:命令模式   别名:动作、事务

模式意图:将一个请求封装为一个对象,从而使你可用不同的请求对客户进行参数化;对请求排队或记录请求日志,以及支持可撤消的操作。

应用场景:

(1)整个调用过程比较繁杂,或者存在多处这种调用。这时,使用Command类对该调用加以封装,便于功能的再利用。

(2)调用前后需要对调用参数进行某些处理。

(3)调用前后需要进行某些额外处理,比如日志,缓存,记录历史操作等。

java例子:

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 interface Command {
public abstract void execute();
}
//生成命令的实现类
public class ConcerteCommand implements Command {
CompanyArmy ca;
ConcerteCommand(CompanyArmy ca){ this.ca = ca; }
public void execute() {ca.sneakAttack();}
}
//指挥者
public class ArySuperior {
Command command;
public void setCommand(Command command) {this.command = command;}
public void startExecuteCommand(){command.execute();}
}
//命令执行者
public class CompanyArmy {
public void sneakAttack(){
System.out.println("三连收到袭击敌人的任务,保证完成任务");
}
}
//客户端
public class Client {
public static void main(String[] args) {
CompanyArmy 三连 = new CompanyArmy();
Command command = new ConcerteCommand(三连);
ArySuperior 指挥官 = new ArySuperior();
指挥官.setCommand(command);
指挥官.startExecuteCommand();
}
}

2.观察者模式

模式名称:观察者模式   别名:依赖、发布、订阅

模式意图:定义对象间的一种一对多的依赖关系,当一个对象的状态发生变化时,所有依赖它的对象得到通知并被自动更新。

应用场景:

(1)当一个抽象模型有两个方面,其中一个方面依赖于另一方面。

(2)当对一个对象的改变需要同时改变其它对象,而不知道具体有多少对象有待改变。

(3)当一个对象必须通知其它对象,而它又不能假定其它对象是谁。

UML类图:



java例子:

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
//抽象观察者
public interface Watcher {
public void update(String str);
}
//生成具体观察者
public class ConcreteWatcher implements Watcher {
public void update(String str) {
System.out.println(str);
}
}
//管理观察者的接口
public interface Watched {
public void addWatcher(Watcher watcher);
public void removeWatcher(Watcher watcher);
public void notifyWatchers(String str);
}
//实现管理观察者
public class ConcreteWatched implements Watched {
private List<Watcher> list = new ArrayList<Watcher>();
public void addWatcher(Watcher watcher) {list.add(watcher);}
public void removeWatcher(Watcher watcher) {list.remove(watcher);}
public void notifyWatchers(String str) {
for(Watcher l : list) l.update(str);
}
}
//客户端
public class Client {
public static void main(String[] args) {
Watched watched = new ConcreteWatched();
Watcher watcher1 = new ConcreteWatcher();
Watcher watcher2 = new ConcreteWatcher();
Watcher watcher3 = new ConcreteWatcher();
watched.addWatcher(watcher1);
watched.addWatcher(watcher2);
watched.addWatcher(watcher3);
watched.notifyWatchers("哈哈");
}
}

3.迭代器模式

模式名称:迭代器模式   别名:游标

模式意图:提供一种方法顺序访问一个聚合对象中的各个元素,而不需要暴露改对象内部表示。

应用场景:

(1)访问一个聚合对象的内容而无需暴露它的内部表示。

(2)支持对聚合对象的多种遍历。

(3)为遍历不同的聚合结构提供统一的接口。

java 例子:

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
//迭代器接口
public interface Iterator {
public Object first();
public Object next();
public Object currentItem();
public boolean isDone();
}
//迭代器实现类
public class ConcreteIterator implements Iterator {
private int currentIndex = 0;
private Vector vector = null;
public ConcreteIterator(final Vector vector){
this.vector = vector;
}
public long applyAsLong(int value) {
return 0;
}
public Object first() {
currentIndex = 0;
return vector.get(currentIndex);
}
public Object next() {
currentIndex++;
return vector.get(currentIndex);
}
public Object currentItem() {
return vector.get(currentIndex);
}
public boolean isDone() {
if (currentIndex >= this.vector.size() - 1) return true;
else return false;
}
}
//组件接口
public interface Aggregat {
public Iterator createIterator();
}
//组件实现类
public class ConcreteAggregat implements Aggregat {
private Vector vector = null;
public Iterator createIterator() {
return new ConcreteIterator(vector);
}
public ConcreteAggregat() {
vector = new Vector();
vector.add("vector1");
vector.add("vector2");
vector.add("vector3");
}
public Vector getVector() {
return vector;
}
public void setVector(Vector vector) {
this.vector = vector;
}
}
//客户端
public class Client {
public static void main(String[] args) {
final Aggregat agg = new ConcreteAggregat();
final Iterator iterator = agg.createIterator();
System.out.println(iterator.first());
while (!iterator.isDone()) {
System.out.println(iterator.next());
}
}
}

,