曹耘豪的博客

适配器模式、装饰者模式、代理模式

  1. 适配器模式(Adaptor)
  2. 装饰者模式(Decorator)
  3. 代理模式(Proxy)
  4. 适配器模式和装饰器模式区别

适配器模式(Adaptor)

适配器模式主要是将一个已知接口转换为我们需要的接口

我们常以电源举例,比如日常的电源的电压是220V(Power220V),设备(Device)需要12V(Power12V),所以我们需要一个12V的适配器(Power12VAdaptor

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
interface Power220V { int output220v(); }
interface Power12V { int output12v(); }

class HomePower implements Power220V {
public int output220v() { return 220; }
}



class Device { Power12V power; }

class Power12VAdaptor implements Power12V {
Power220V input;

public int output12v() {
return input.output220v() / 220 * 12
}
}

Power220V homePower = new HomePower();

Power12V adaptorOutput = new Power12VAdaptor(homePower);

Device device = new Device(adaptorOutput)

装饰者模式(Decorator)

装饰者模式通常是增强现有接口的功能

比如我们想在一个类执行方法前打印执行耗时

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
interface A { void doSomething(); }

class ALoggerDecorator implements A {
ClassA inner;

public void doSomething() {
System.out.println('doSomething begin');
long start = System.currentMillis();
inner.doSomething();
long end = System.currentMillis();
System.out.format('doSomething end. Cost %dms', end - start);
}
}

class ClassA implements A { public void doSomething() {} }

A a = new ALoggerDecorator(new ClassA());

代理模式(Proxy)

代理模式和装饰者模式类似,都是增强同一个接口,但代理模式侧重于管理

适配器模式和装饰器模式区别

   /