Java开发中的适配器(Adapter)和装饰器(Decorator)是两种常用的设计模式。适配器模式主要用于使原本不兼容的类之间能够协同工作,而装饰器模式则是在不改变接口的前提下增强一个对象的功能。
java中的适配器模式通常是通过实现接口或继承抽象类来实现的。例如下面这段代码就是一个将Enumeration接口转换为Iterator接口的适配器。
public class EnumerationIteratorimplements Iterator {private Enumeration enumeration; public EnumerationIterator(Enumeration enumeration) {this.enumeration = enumeration;}public boolean hasNext() {return enumeration.hasMoreElements();}public E next() {return enumeration.nextElement();}public void remove() {throw new UnsupportedOperationException();}}
可以看到,通过实现Iterator接口并在构造函数中传入一个Enumeration对象,我们就能够将Enumeration对象适配为Iterator接口了。
相比适配器模式,装饰器模式则主要用于在运行时动态地为一个对象添加新的行为。例如下面这段代码就是一个简单的装饰器模式的实现:
public class DecoratorTest {public static void main(String[] args) {Beverage beverage = new Espresso();beverage = new Mocha(beverage);beverage = new Whip(beverage);System.out.println(beverage.getDescription() + " $" + beverage.cost());}}interface Beverage {String getDescription();double cost();}class Espresso implements Beverage {public String getDescription() {return "Espresso";}public double cost() {return 1.99;}}abstract class CondimentDecorator implements Beverage {protected Beverage beverage;public CondimentDecorator(Beverage beverage) {this.beverage = beverage;}}class Mocha extends CondimentDecorator {public Mocha(Beverage beverage) {super(beverage);}public String getDescription() {return beverage.getDescription() + ", Mocha";}public double cost() {return beverage.cost() + 0.20;}}class Whip extends CondimentDecorator {public Whip(Beverage beverage) {super(beverage);}public String getDescription() {return beverage.getDescription() + ", Whip";}public double cost() {return beverage.cost() + 0.10;}}
可以看到,我们定义了一个饮料(Beverage)接口,然后通过对Espresso类进行装饰,添加了摩卡和奶泡这两种调料。通过这种方式,我们既不需要修改Espresso类的代码,也能在运行时动态地为其添加新的行为。