设计模式

创建型

单例

确保一个类只有一个实例,并提供该实例的全局访问点。

  1. 懒汉式-线程不安全

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    /**
    * @desc 懒汉式-线程不安全
    * @Author xw
    * @Date 2019/11/15
    */
    public class SingletonOne {
    private static SingletonOne instance;
    private SingletonOne() {

    }
    public static SingletonOne getInstance() {
    if (instance == null) {
    instance = new SingletonOne();
    }
    return instance;
    }
    }
  2. 饿汉式-线程安全

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    /**
    * @desc 饿汉式-线程安全
    * @Author xw
    * @Date 2019/11/15
    */
    public class SingletonTwo {
    private static SingletonTwo instance = new SingletonTwo();
    private SingletonTwo() {

    }
    public static SingletonTwo getInstance() {
    return instance;
    }
    }
  3. 懒汉式-线程安全

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    /**
    * @desc 懒汉式-线程安全
    * @Author xw
    * @Date 2019/11/15
    */
    public class SingletonThree {
    private static SingletonThree instance;
    private SingletonThree() {

    }
    public static synchronized SingletonThree getInstance() {
    if (instance == null) {
    instance = new SingletonThree();
    }
    return instance;
    }
    }
  4. 双重校验锁-线程安全

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    /**
    * @desc 双重校验锁-线程安全
    * @Author xw
    * @Date 2019/11/15
    */
    public class SingletonFour {
    private volatile static SingletonFour instance;
    private SingletonFour() {

    }
    public static SingletonFour getInstance() {
    if (instance == null) {
    synchronized (SingletonFour.class) {
    if (instance == null) {
    instance = new SingletonFour();
    }
    }
    }
    return instance;
    }
    }
  5. 静态内部类实现

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    /**
    * @desc 静态内部类
    * @Author xw
    * @Date 2019/11/15
    */
    public class SingletonFive {
    private static class SingletonHolder {
    private static final SingletonFive INSTANCE = new SingletonFive();
    }
    public static SingletonFive getInstance() {
    return SingletonHolder.INSTANCE;
    }
    }
  6. 枚举

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    /**
    * @desc 枚举
    * @Author xw
    * @Date 2019/11/15
    */
    public enum SingletonSix {
    INSTANCE;
    private String objectName;
    public String getObjectName() {
    return objectName;
    }
    public void setObjectName(String objectName) {
    this.objectName = objectName;
    }
    public static void main(String[] args) {
    SingletonSix firstSingleton = SingletonSix.INSTANCE;
    firstSingleton.setObjectName("firstName");
    System.out.println(firstSingleton.getObjectName());
    SingletonSix secondSingleton = SingletonSix.INSTANCE;
    secondSingleton.setObjectName("secondName");
    System.out.println(firstSingleton.getObjectName());
    System.out.println(secondSingleton.getObjectName());
    }
    }

简单工厂

在创建一个对象时不向客户暴露内部细节,并提供一个创建对象的通用接口。

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
/**
* @desc 测试类
* @Author xw
* @Date 2019/11/15
*/
public class Client {
public static void main(String[] args) {
// 正常创建
int type = 1; // 1-苹果,2-杯子,3-手机
Product product;
if (type == 1) {
product = new Apple();
} else if (type == 2) {
product = new Cup();
} else {
product = new Phone();
}
System.out.println(product.getClass().getName()); // Apple

// 使用简单工厂
Product productFactory = SimpleFactory.createProduct(2);
System.out.println(productFactory.getClass().getName()); // Cup
}
}
// 商品
public interface Product {
}
public class Phone implements Product {
}
public class Cup implements Product{
}
public class Apple implements Product {
}
/**
* @desc 简单工厂
* @Author xw
* @Date 2019/11/15
*/
public class SimpleFactory {
// 1-苹果,2-杯子,3-手机
public static Product createProduct(int type) {
if (type == 1) {
return new Apple();
} else if (type == 2) {
return new Cup();
}
return new Phone();
}
}

工厂方法

定义了一个创建对象的接口,但由子类决定要实例化哪个类。工厂方法把实例化操作推迟到子类。

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
/**
* @desc 测试类
* @Author xw
* @Date 2019/11/15
*/
public class Client {
public static void main(String[] args) {
Factory factory = new CupFactory();
factory.dosomething();
factory = new PhoneFactory();
factory.dosomething();
}
}
public class CupFactory extends Factory {
@Override
public Product factoryMethod() {
return new Cup();
}
}
public class PhoneFactory extends Factory {
@Override
public Product factoryMethod() {
return new Phone();
}
}

抽象工厂

提供一个接口,用于创建相关的对象家族。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
/**
* @desc 测试类
* @Author xw
* @Date 2019/11/15
*/
public class Client {
public static void main(String[] args) {
AbstractFactory abstractFactory = new ConcreteFactory1();
AbstractProductA productA = abstractFactory.createProductA();
AbstractProductB productB = abstractFactory.createProductB();
System.out.println(productA.getClass().getName()); // ProductA1
System.out.println(productB.getClass().getName()); // ProductB1
abstractFactory = new ConcreteFactory2();
System.out.println(abstractFactory.createProductA().getClass().getName()); // ProductA2
System.out.println(abstractFactory.createProductB().getClass().getName()); // ProductB2
}
}

原型模式

使用原型实例指定要创建对象的类型,通过复制这个原型来创建新对象。

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
/**
* @desc Client
* @Author xw
* @Date 2019/11/15
*/
public class Client {
public static void main(String[] args) {
Prototype prototype = new ConcretePrototype("abc");
Prototype clone = prototype.myClone();
System.out.println(clone.toString());
}
}
public class ConcretePrototype extends Prototype {
private String filed;
public ConcretePrototype(String filed) {
this.filed = filed;
}
@Override
Prototype myClone() {
return new ConcretePrototype(filed);
}
@Override
public String toString() {
return filed;
}
}
/**
* @desc 原型模式
* @Author xw
* @Date 2019/11/15
*/
public abstract class Prototype {
abstract Prototype myClone();
}

行为型

责任链

使多个对象都有机会处理请求,从而避免请求的发送者和接收者之间的耦合关系。将这些对象连成一条链,并沿着这
条链发送该请求,直到有一个对象处理它为止。

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
/**
* @desc 测试类
* @Author xw
* @Date 2019/11/15
*/
public class Client {
public static void main(String[] args) {
Handler handler1 = new ConcreteHandler1(null);
Handler handler2 = new ConcreteHandler2(handler1);
Request request1 = new Request(RequestType.TYPE1, "request1");
handler2.handleRequest(request1);
Request request2 = new Request(RequestType.TYPE2, "request2");
handler2.handleRequest(request2);
}
}
/**
* @desc ConcreteHandler1
* @Author xw
* @Date 2019/11/15
*/
public class ConcreteHandler1 extends Handler {
public ConcreteHandler1(Handler successor) {
super(successor);
}
@Override
public void handleRequest(Request request) {
if (request.getType() == RequestType.TYPE1) {
System.out.println(request.getName() + " is handle by ConcreteHandler1");
return;
}
if (successor != null) {
successor.handleRequest(request);
}
}
}
public class ConcreteHandler2 extends Handler {
public ConcreteHandler2(Handler successor) {
super(successor);
}
@Override
public void handleRequest(Request request) {
if (request.getType() == RequestType.TYPE2) {
System.out.println(request.getName() + " is handle by ConcreteHandler2");
return;
}
if (successor != null) {
successor.handleRequest(request);
}
}
}

命令

将命令封装成对象中,具有以下作用:

  • 使用命令来参数化其它对象
  • 将命令放入队列中进行排队
  • 将命令的操作记录到日志中
  • 支持可撤销的操作
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
/**
* @desc Client
* @Author xw
* @Date 2019/11/15
*/
public class Client {
public static void main(String[] args) {
Invoker invoker = new Invoker();
Light light = new Light();
Command lightOnCommand = new LightOnCommand(light);
Command lightOffCommand = new LightOffCommand(light);
invoker.setOnCommand(lightOnCommand, 0);
invoker.setOffCommand(lightOffCommand, 0);
invoker.onButtonWasPushed(0); // 第0个按钮被打开
invoker.offButtonWasPushed(0); // 第0个按钮被关闭
}
}

解释器

为语言创建解释器,通常由语言的语法和语法分析来定义。

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
/**
* @desc Client
* @Author xw
* @Date 2019/11/15
*/
public class Client {
public static void main(String[] args) {
Expression define = buildInterpreterTree();
String context1 = "D A";
String context2 = "A B";
System.out.println(define.interpret(context1)); // true
System.out.println(define.interpret(context2)); // false
}
// D and (A or (B C))
public static Expression buildInterpreterTree() {
// Literal
Expression a = new TerminalExpression("A");
Expression b = new TerminalExpression("B");
Expression c = new TerminalExpression("C");
Expression d = new TerminalExpression("D");
// B C
Expression bOrC = new OrExpression(b, c);
// A or (B C)
Expression aOrBC = new OrExpression(a, bOrC);
// D and (A or (B C))
return new AndExpression(d, aOrBC);
}
}

迭代器

提供一种顺序访问聚合对象元素的方法,并且不暴露聚合对象的内部表示。

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 class Client {
public static void main(String[] args) {
Aggregate aggregate = new ConcreteAggregate();
Iterator<Integer> iterator = aggregate.createIterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
}
}
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<>(items);
}
}
public class ConcreteIterator<T> implements Iterator {
private T[] items;
private int position = 0;
public ConcreteIterator(T[] items) {
this.items = items;
}
@Override
public T next() {
return items[position++];
}
@Override
public boolean hasNext() {
return position < items.length;
}
}

中介者

集中相关对象之间复杂的沟通和控制方式。

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
public class Client {
public static void main(String[] args) {
Alarm alarm = new Alarm();
CoffeePot coffeePot = new CoffeePot();
Calender calender = new Calender();
Sprinkler sprinkler = new Sprinkler();
Mediator mediator = new ConcreteMediator(alarm, coffeePot, calender, sprinkler);
// 闹钟事件到达,调用中介都就可以操作相关对象
alarm.onEvent(mediator);
}
}
public class ConcreteMediator extends Mediator {
private Alarm alarm;
private CoffeePot coffeePot;
private Calender calender;
private Sprinkler sprinkler;
public ConcreteMediator(Alarm alarm, CoffeePot coffeePot, Calender calender, Sprinkler sprinkler) {
this.alarm = alarm;
this.coffeePot = coffeePot;
this.calender = calender;
this.sprinkler = sprinkler;
}
@Override
public void doEvent(String eventType) {
switch (eventType) {
case "alarm":
doAlarmEvent();
break;
case "coffeePot":
doCoffeePotEvent();
break;
case "calender":
doCalenderEvent();
break;
default:
doSprinklerEvent();
}
}
private void doSprinklerEvent() {
this.sprinkler.doSprinkler();
}
private void doCalenderEvent() {
this.calender.doCalender();
}
private void doCoffeePotEvent() {
this.coffeePot.doCoffeePot();
}
private void doAlarmEvent() {
alarm.doAlarm();
coffeePot.doCoffeePot();
calender.doCalender();
sprinkler.doSprinkler();
}
}

观察者

定义对象之间的一对多依赖,当一个对象状态改变时,它的所有依赖都会收到通知并且自动更新状态。主题(Subject)是被观察的对象,而其所有依赖者(Observer)称为观察者。

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
public class WeatherStation {
public static void main(String[] args) {
WeatherData weatherData = new WeatherData();
CurrentConditionsDisplay currentConditionsDisplay = new CurrentConditionsDisplay(weatherData);
StatisticsDisplay statisticsDisplay = new StatisticsDisplay(weatherData);
weatherData.setMeasurements(0, 0, 0);
weatherData.setMeasurements(1, 1, 1);
}
}
public interface Subject {
void registerObserver(Observer o);
void removeObserver(Observer o);
void notifyObserver();
}
public interface Observer {
void update(float temp, float humidity, float pressure);
}
public class WeatherData implements Subject {
private List<Observer> observers;
public void setMeasurements(float temperature, float humidity, float pressure) {
this.temperature = temperature;
this.humidity = humidity;
this.pressure = pressure;
notifyObserver();
}
@Override
public void registerObserver(Observer o) {
observers.add(o);
}
@Override
public void notifyObserver() {
for (Observer o : observers) {
o.update(temperature, humidity, pressure);
}
}
}