文章目录
  1. 1. 装饰者模式
  2. 2. 单例模式

装饰者模式

我就是我,“装饰”后颜色不一样的烟火。

  • 定义:动态地将责任附加到对象上,若要扩展功能,装饰着提供了比继承更有弹性的方案
  • 实际操作:定义抽象组件,继承了抽象组件的抽象装饰者,和相应的实际组件和实际装饰者,将组件对象作为参数放入装饰者类中,得到一个装饰过的对象
  • 实际应用:Java I/O

例如:
抽象组件InputStream
具体组件:FileInputStream、StringBufferInputStream、ByteArrayInputStream
抽象装饰者:FilterInputStream
具体装饰者:BufferedInputStream、LineNumberInputStream

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
public class 装饰者模式 {
public static void main(String[] args) {
Beverage beverage = new Espresso();
System.out.println(beverage.getDescription() + "$" + beverage.cost());
beverage = new Mocha(beverage);
System.out.println(beverage.getDescription() + "$" + beverage.cost());
}
}
//抽象组件
abstract class Beverage {
String description = "Unknown Beverage";
public String getDescription() {
return description;
}
public abstract double cost();
}
//抽象装饰者(必须扩展自Beverage类)
abstract class Decorator extends Beverage {
//重新实现getDescription
public abstract String getDescription();
}
//具体组件
class Espresso extends Beverage {
public Espresso() {
description = "Espresso";
}
@Override
public double cost() {
return 1.99;
}
}
//具体装饰者
class Mocha extends Decorator {
Beverage beverage;
public Mocha(Beverage beverage) {
this.beverage = beverage;
}
public String getDescription() {
return beverage.getDescription() + ",Mocha";
}
public double cost() {
return .20 + beverage.cost();
}
}

单例模式

无论何时出生,总是天下“无双”。

  • 定义:确保一个类只有一个实例,并且提供一个全局访问点。
  • 实际操作:根据是否一开始就生成实例分为“懒汉”和“饿汉”方式,此外出于多线程的考虑需要加上双重校验锁,或者使用内部类实现
  • 实际应用:线程池、缓存、日志、驱动等
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
//饿汉模式
class SingleTon_eager {
private static SingleTon_eager instance = new SingleTon_eager();
private SingleTon_eager() {}
public static SingleTon_eager getInstance() {
return instance;
}
}
//懒汉模式(多线程,双重锁)
class SingleTon_Lazy_Threads {
private volatile static SingleTon_Lazy_Threads instance;
private SingleTon_Lazy_Threads() {}
public static SingleTon_Lazy_Threads getInstance() {
if (instance == null) {
synchronized (SingleTon_Lazy_Threads.class) {
if (instance == null) {
instance = new SingleTon_Lazy_Threads();
}
}
}
return instance;
}
}
//(懒汉模式,内部类)
class SingleTon_Lazy_Threads_Best {
private static class SingleTonHolder {
private static SingleTon_Lazy_Threads_Best instance = new SingleTon_Lazy_Threads_Best();
}
private SingleTon_Lazy_Threads_Best() {}
public static SingleTon_Lazy_Threads_Best getInstance() {
return SingleTonHolder.instance;
}
}
文章目录
  1. 1. 装饰者模式
  2. 2. 单例模式