设计模式分析

[TOC]

创建型

单例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public class Singleton {
private volatile static Singleton uniqueInstance;
private Singleton() {
}
public static Singleton getUniqueInstance() {
if (uniqueInstance == null) {
synchronized (Singleton.class) {
if (uniqueInstance == null) {
uniqueInstance = new Singleton();
}
}
}
return uniqueInstance;
}
}

简单工厂

1
2
3
4
5
6
7
8
9
10
11
12
public interface Product {
}
public class ConcreteProduct implements Product{
}
public class simpleFactory {
public Product createProduct(int type) {
if(type == 1) {
return new ConcreteProduct();
}
return null;
}
}

工厂

1
2
3
4
5
6
7
8
9
10
11
12
13
public interface Product {
}
public class ConcreteProduct implements Product {
}
public abstract class Factory {
public abstract Product createProduct();
}
public class ConcreteFactory extends Factory{
@Override
public Product createProduct() {
return new ConcreteProduct();
}
}

建造者

我们先说一个生活中的小例子,当我们在外面饭店吃饭时,比如点个水煮肉片,这家店可能会辣一点、那家店可能会咸一点、对面那家可能放青菜、隔壁那家可能放菠菜,每家店做出来的都不一样,明明都是水煮肉片却有不同的做法,如果都一样就不会说这家难吃那家好吃了。那再看快餐店,比如KFC,我们点个至尊虾堡,所有人不管在哪个城市哪家店,做法、味道都是一样的,为什么呢,因为它用料、时间、温度等等都是严格规定的,我们只需要下订单就行了,这就是一个建造者模式

image-20211105202614707

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
public class Director {

public void Construct(Builder builder) {
builder.BuildPartA();
builder.BuildPartB();
}

}
public abstract class Builder {

public abstract void BuildPartA(); //产品的A部件
public abstract void BuildPartB(); //产品的B部件
public abstract Product getResult(); //获取产品建造后结果

}
public class ConcreteBuilder1 extends Builder {

private Product product = new Product();

//设置产品零件
@Override
public void BuildPartA() {
product.add("部件A");
}

@Override
public void BuildPartB() {
product.add("部件B");
}

//组建一个产品
@Override
public Product getResult() {
return product;
}

}
public class Client {

public static void main(String[] args) {

Director director = new Director();
Builder builder1 = new ConcreteBuilder1();
Builder builder2 = new ConcreteBuilder2();

//指挥者用ConcreteBuilder1的方法来建造产品
director.Construct(builder1);
Product product1 = builder1.getResult();
product1.show();

//指挥者用ConcreteBuilder2的方法来建造产品
director.Construct(builder2);
Product product2 = builder2.getResult();
product2.show();

}

}

原型

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
public abstract class ProtoType {
abstract ProtoType myclone() ;
}
public class ConcreteProto extends ProtoType{
private String str;

public ConcreteProto(String str) {
this.str = str;
}

@Override
public String toString() {
return "ConcreteProto{" +
"str='" + str + '\'' +
'}';
}

@Override
ProtoType myclone() {
return new ConcreteProto(str);
}
}

行为型

责任链

image-20211105212239282

  • 链上的每个对象都有机会处理请求
  • 链上的每个对象都持有下一个要处理对象的引用
  • 链上的某个对象无法处理当前请求,那么它会把相同的请求传给下一个对象
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
public class PreparationList {

/**
* 是否洗脸
*/
private boolean washFace;

/**
* 是否洗头
*/
private boolean washHair;

public boolean isWashFace() {
return washFace;
}

public void setWashFace(boolean washFace) {
this.washFace = washFace;
}

public boolean isWashHair() {
return washHair;
}

public void setWashHair(boolean washHair) {
this.washHair = washHair;
}
@Override
public String toString() {
return "ThingList [washFace=" + washFace + ", washHair=" + washHair + ", haveBreakfast=" + haveBreakfast + "]";
}

}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
public abstract class AbstractPrepareFilter {

private AbstractPrepareFilter nextPrepareFilter;

public AbstractPrepareFilter(AbstractPrepareFilter nextPrepareFilter) {
this.nextPrepareFilter = nextPrepareFilter;
}

public void doFilter(PreparationList preparationList, Study study) {
prepare(preparationList);

if (nextPrepareFilter == null) {
study.study();
} else {
nextPrepareFilter.doFilter(preparationList, study);
}
}

public abstract void prepare(PreparationList preparationList);

}
1
2
3
4
5
6
7
public class Study {

public void study() {
System.out.println("学习");
}

}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public class WashFaceFilter extends AbstractPrepareFilter {

public WashFaceFilter(AbstractPrepareFilter nextPrepareFilter) {
super(nextPrepareFilter);
}

@Override
public void prepare(PreparationList preparationList) {
if (preparationList.isWashFace()) {
System.out.println("洗脸");
}

}

}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public class WashHairFilter extends AbstractPrepareFilter {

public WashHairFilter(AbstractPrepareFilter nextPrepareFilter) {
super(nextPrepareFilter);
}

@Override
public void prepare(PreparationList preparationList) {
if (preparationList.isWashHair()) {
System.out.println("洗头");
}

}

}
1
2
3
4
5
6
7
8
9
10
11
12
public class test1 {
public static void main(String[] args) {
PreparationList preparationList = new PreparationList();
preparationList.setWashFace(true);
preparationList.setWashHair(false);
Study study = new Study();
AbstractPrepareFilter washFaceFilter = new WashFaceFilter(null);
AbstractPrepareFilter washHairFilter = new WashHairFilter(washFaceFilter);

washHairFilter.doFilter(preparationList, study);
}
}

迭代器

image-20211105230627238

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
public interface Aggregate {
Iterator createIterator();
}
public class ConcreteAggregate implements Aggregate {
private Integer[] items;
public ConcreteAggregate() {
items = new Integer[10];
for (int i = 0; i < items.length; i++) {
items[i] = i;
}
}
@Override
public Iterator createIterator() {
return new ConcreteIterator<Integer>(items);
}
}
public interface Iterator<Item> {
Item next();
boolean hasNext();
}
public class ConcreteIterator<Item> implements Iterator {
private Item[] items;
private int position = 0;
public ConcreteIterator(Item[] items) {
this.items = items;
}
@Override
public Object next() {
return items[position++];
}
@Override
public boolean hasNext() {
return position < items.length;
}
}

观察者

主题(Subject)具有注册和移除观察者、并通知所有观察者的功能,主题是通过维护一张观察者列表来实现这些操
作的。
观察者(Observer)的注册功能需要调用主题的 registerObserver() 方法。

image-20211105234424187

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
public interface Observer {
void update(int temp);
}
public class ConcreteObserver1 implements Observer {
public ConcreteObserver1(Subject subject) {
subject.register(this);
}

@Override
public void update(int temp) {
System.out.println(temp);
}
}
public interface Subject {
void register(Observer o);
void remove(Observer o);
void notify1();
}
public class ConcreteSubject implements Subject{
private List<Observer> observerList;
private int tmp;
public ConcreteSubject(List<Observer> observerList) {
this.observerList = observerList;
}
public void display(int temp) {
this.tmp = temp;
}
@Override
public void register(Observer o) {
observerList.add(o);
}

@Override
public void remove(Observer o) {
observerList.remove(o);
}

@Override
public void notify1() {
for(Observer o : observerList) {
o.update(tmp);
}
}
}

策略

image-20211105235519959

1
2
3
4
public interface Strategy
{
public void useStrategy();
}
1
2
3
4
5
6
7
public class StrategyA implements Strategy
{
public void useStrategy()
{
System.out.println("StrategyA.useStrategy()");
}
}
1
2
3
4
5
6
7
public class StrategyB implements Strategy
{
public void useStrategy()
{
System.out.println("StrategyB.useStrategy()");
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
public class Context
{
private Strategy strategy;

public Context(Strategy strategy)
{
this.strategy = strategy;
}

public void strategyMethod()
{
strategy.useStrategy();
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
public class TestMain
{
public static void main(String[] args)
{
Strategy strategyA = new StrategyA();
Strategy strategyB = new StrategyB();

Context context = new Context(strategyA);
context.strategyMethod();
context = new Context(strategyB);
context.strategyMethod();
}
}

状态模式

状态模式把所研究的对象的行为包装在不同的状态对象里,每一个状态对象都属于一个抽象状态类的一个子类。状态模式的意图是让一个对象在其内部状态改变的时候,其行为也随之改变。状态模式的示意性类图如下所示:

image-20211119151803506

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
public class Context {
//持有一个State类型的对象实例
private State state;

public void setState(State state) {
this.state = state;
}
/**
* 用户感兴趣的接口方法
*/
public void request(String sampleParameter) {
//转调state来处理
state.handle(sampleParameter);
}
}
public interface State {
/**
* 状态对应的处理
*/
public void handle(String sampleParameter);
}
public class ConcreteStateA implements State {

@Override
public void handle(String sampleParameter) {

System.out.println("ConcreteStateA handle :" + sampleParameter);
}

}
public class ConcreteStateB implements State {

@Override
public void handle(String sampleParameter) {

System.out.println("ConcreteStateB handle :" + sampleParameter);
}

}
public class Client {

public static void main(String[] args){
//创建状态
State state = new ConcreteStateB();
//创建环境
Context context = new Context();
//将状态设置到环境中
context.setState(state);
//请求
context.request("test");
}
}

备忘录

 备忘录对象是一个用来存储另外一个对象内部状态的快照的对象。备忘录模式的用意是在不破坏封装的条件下,将一个对象的状态捕捉(Capture)住,并外部化,存储起来,从而可以在将来合适的时候把这个对象还原到存储起来的状态。备忘录模式常常与命令模式和迭代子模式一同使用。

image-20211119152000305

命令模式

 每一个命令都是一个操作:请求的一方发出请求要求执行一个操作;接收的一方收到请求,并执行操作。命令模式允许请求的一方和接收的一方独立开来,使得请求的一方不必知道接收请求的一方的接口,更不必知道请求是怎么被接收,以及操作是否被执行、何时被执行,以及是怎么被执行的。

image-20211119152401118

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
public class Receiver {
/**
* 真正执行命令相应的操作
*/
public void action(){
System.out.println("执行操作");
}
}
public interface Command {
/**
* 执行方法
*/
void execute();
}
public class ConcreteCommand implements Command {
//持有相应的接收者对象
private Receiver receiver = null;
/**
* 构造方法
*/
public ConcreteCommand(Receiver receiver){
this.receiver = receiver;
}
@Override
public void execute() {
//通常会转调接收者对象的相应方法,让接收者来真正执行功能
receiver.action();
}

}
public class Invoker {
/**
* 持有命令对象
*/
private Command command = null;
/**
* 构造方法
*/
public Invoker(Command command){
this.command = command;
}
/**
* 行动方法
*/
public void action(){

command.execute();
}
}

结构型

适配器

image-20211106193659420

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 Target {

public void request();

}
//已经存在的, 并且具有特殊功能的类, 但是不符合我们既有的标准的接口的类
public class Adaptee {
public void specificRequest() {
System.out.println("被适配类, 我是两孔插座, 具有特殊的功能");
}
}
// 装饰类, 直接关联被适配器类, 同时实现标准接口
public class Adapter implements Target {

private Adaptee adaptee;

// 通过构造函数传入被适配类对象
public Adapter(Adaptee adaptee) {
this.adaptee = adaptee;
}

@Override
public void request() {
System.out.println("我是适配器类, 我能适配任何两孔插座, 让它正常工作");
// 这里使用委托的方式完成特殊的功能
this.adaptee.specificRequest();
}
}
public class App
{
public static void main( String[] args ) {
// 使用特殊功能类, 即适配类
// 需要先创建一个呗适配类的对象作为参数
Target target = new Adapter(new Adaptee());
target.request();
}
}

桥接器

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 abstract class Abstraction {

protected Implementor impl;

public Abstraction(Implementor impl){
this.impl = impl;
}
//示例方法
public void operation(){

impl.operationImpl();
}
}
public class RefinedAbstraction extends Abstraction {

public RefinedAbstraction(Implementor impl) {
super(impl);
}
//其他的操作方法
public void otherOperation(){

}
}
public abstract class Implementor {
/**
* 示例方法,实现抽象部分需要的某些具体功能
*/
public abstract void operationImpl();
}
public class ConcreteImplementorA extends Implementor {

@Override
public void operationImpl() {
//具体操作
}

}

装饰器

image-20211106000624467

1
2
3
4
5
public interface Cook {

public void cookDinner();

}
1
2
3
4
5
6
7
8
public class ChineseCook implements Cook {

@Override
public void cookDinner() {
System.out.println("中国人做晚饭");
}

}
1
2
3
4
5
public abstract class FilterCook implements Cook {

protected Cook cook;

}
public class WashHandsCook extends FilterCook {
public WashHandsCook(Cook cook) {
    this.cook = cook;
}

@Override
public void cookDinner() {
    System.out.println("先洗手");
    cook.cookDinner();
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
public class WashHearCook extends FilterCook {

public WashHearCook(Cook cook) {
this.cook = cook;
}

@Override
public void cookDinner() {
System.out.println("先洗头");
cook.cookDinner();
}

}
Cook cook0 = new WashHandsCook(new ChineseCook());
Cook cook1 = new WashHearCook(new ChineseCook());

cook0.cookDinner();
cook1.cookDinner();

代理

image-20211114103659372

1
2
3
4
public abstract class AbstractObject {
//操作
public abstract void operation();
}
1
2
3
4
5
6
7
public class RealObject extends AbstractObject {
@Override
public void operation() {
//一些操作
System.out.println("一些操作");
}
}
1
2
3
4
5
6
7
8
9
10
11
public class ProxyObject extends AbstractObject{
RealObject realObject = new RealObject();
@Override
public void operation() {
//调用目标对象之前可以做相关操作
System.out.println("before");
realObject.operation();
//调用目标对象之后可以做相关操作
System.out.println("after");
}
}
1
2
3
4
5
6
7
8
9
public class Client {

public static void main(String[] args) {
// TODO Auto-generated method stub
AbstractObject obj = new ProxyObject();
obj.operation();
}

}

组合

合成模式把部分和整体的关系用树结构表示出来。合成模式使得客户端把一个个单独的成分对象和由它们复合而成的合成对象同等看待。

image-20211114104309233

image-20211114104331473

1
2
3
4
5
6
public interface Component {
/**
* 输出组建自身的名称
*/
public void printStruct(String preStr);
}
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
public class Composite implements Component {
/**
* 用来存储组合对象中包含的子组件对象
*/
private List<Component> childComponents = new ArrayList<Component>();
/**
* 组合对象的名字
*/
private String name;
/**
* 构造方法,传入组合对象的名字
* @param name 组合对象的名字
*/
public Composite(String name){
this.name = name;
}
/**
* 聚集管理方法,增加一个子构件对象
* @param child 子构件对象
*/
public void addChild(Component child){
childComponents.add(child);
}
/**
* 聚集管理方法,删除一个子构件对象
* @param index 子构件对象的下标
*/
public void removeChild(int index){
childComponents.remove(index);
}
/**
* 聚集管理方法,返回所有子构件对象
*/
public List<Component> getChild(){
return childComponents;
}
/**
* 输出对象的自身结构
* @param preStr 前缀,主要是按照层级拼接空格,实现向后缩进
*/
@Override
public void printStruct(String preStr) {
// 先把自己输出
System.out.println(preStr + "+" + this.name);
//如果还包含有子组件,那么就输出这些子组件对象
if(this.childComponents != null){
//添加两个空格,表示向后缩进两个空格
preStr += " ";
//输出当前对象的子对象
for(Component c : childComponents){
//递归输出每个子对象
c.printStruct(preStr);
}
}

}

}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public class Leaf implements Component {
/**
* 叶子对象的名字
*/
private String name;
/**
* 构造方法,传入叶子对象的名称
* @param name 叶子对象的名字
*/
public Leaf(String name){
this.name = name;
}
/**
* 输出叶子对象的结构,叶子对象没有子对象,也就是输出叶子对象的名字
* @param preStr 前缀,主要是按照层级拼接的空格,实现向后缩进
*/
@Override
public void printStruct(String preStr) {
// TODO Auto-generated method stub
System.out.println(preStr + "-" + name);
}

}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
public class Client {
public static void main(String[]args){
Composite root = new Composite("服装");
Composite c1 = new Composite("男装");
Composite c2 = new Composite("女装");

Leaf leaf1 = new Leaf("衬衫");
Leaf leaf2 = new Leaf("夹克");
Leaf leaf3 = new Leaf("裙子");
Leaf leaf4 = new Leaf("套装");

root.addChild(c1);
root.addChild(c2);
c1.addChild(leaf1);
c1.addChild(leaf2);
c2.addChild(leaf3);
c2.addChild(leaf4);

root.printStruct("");
}
}

外观模式

提供了一个统一的接口,用来访问子系统中的一群接口,从而让子系统更容易使用。

1
2
3
4
5
6
7
8
9
10
11
public class SubSystem {
public void turnOnTV() {
System.out.println("turnOnTV()");
}
public void setCD(String cd) {
System.out.println("setCD( " + cd + " )");
}
public void startWatching(){
System.out.println("startWatching()");
}
}
1
2
3
4
5
6
7
8
public class Facade {
private SubSystem subSystem = new SubSystem();
public void watchMovie() {
subSystem.turnOnTV();
subSystem.setCD("a movie");
subSystem.startWatching();
}
}