动态添加对象功能。通过委托机制,复用系统中的各个组件,在运行时,可以讲这些功能组件进行叠加,从而组成一个“超级对象”。
代码复用应该尽可能使用组合(委托),而不是使用继承。因为继承是一种紧密耦合,任何父类的改动都会影响到子类,不利于系统维护。装饰者模式可以有效的分离性能组件和功能组件,从而有效提升模块的可维护性和复用性。
public interface IBuilding { public String getDetails(); }Building.java
public class Building implements IBuilding{ public String getDetails() { // TODO Auto-generated method stub return "一间普通的房子"; } }BuildingDecorator.java 装饰者的抽象类,持有一个被装饰对象
public abstract class BuildingDecorator implements IBuilding{ IBuilding building; public BuildingDecorator(IBuilding building) { this.building=building; } }LightingDecorator.java 灯饰装饰
public class LightingDecorator extends BuildingDecorator { public LightingDecorator(IBuilding building) { super(building); } public String getDetails() { // TODO Auto-generated method stub StringBuffer sb=new StringBuffer(); sb.append(building.getDetails()); sb.append(",装上灯饰"); return sb.toString(); } }FlowerDecorator.java 鲜花装饰
public class FlowerDecorator extends BuildingDecorator { public FlowerDecorator(IBuilding building) { super(building); } public String getDetails() { // TODO Auto-generated method stub StringBuffer sb=new StringBuffer(); sb.append(building.getDetails()); sb.append(",放上几盆花"); return sb.toString(); } }
public class LearnDecorator { public static void main(String[] args) { //通过层层构造,将装饰者添加到被装饰对象上,可以有选择性的添加装饰者 IBuilding building=new LightingDecorator(new FlowerDecorator(new Building())); System.out.println(building.getDetails()); } }运行结果:
一间普通的房子,放上几盆花,装上灯饰
DataOutputStream outputStream=new DataOutputStream(new BufferedOutputStream(new FileOutputStream("f:/example.txt"))); outputStream.writeChars("hello world");