- 装饰者模式
利用继承和组合的方式实现给一个类添加不同功能
例子:
需求:手机为父类,子类有小米、华为,给他们装饰内存卡、充电宝等小类
手机父类:
小米:public abstract class Phone { public String description = ""; public String getDescription() { return description; } public abstract double cost() ; }
抽象装饰者:public class XiaoMi extends Phone{ public XiaoMi() { description = "小米手机"; } @Override public double cost() { // TODO Auto-generated method stub return 2000; } }
电池:public abstract class Attachment extends Phone{ //组合方式 Phone phn; public Attachment(Phone ph) { this.phn = ph; } @Override public String getDescription() { // TODO Auto-generated method stub return phn.getDescription(); } @Override public double cost() { return phn.cost(); } }
调用:public class Battery extends Attachment{ public Battery(Phone ph) { super(ph); } @Override public String getDescription() { // TODO Auto-generated method stub return super.getDescription() + "电池"; } @Override public double cost() { // TODO Auto-generated method stub return super.cost() + 50D; } }
public class phoneTest{ public static void main(String[] args) { Phone p1 =new XiaoMi(); p1 = new Battery(p1); String str = p1.getDescription(); p1.cost(); System.out.println(str+Double.toString(p1.cost())); } }
从装饰者模式的理解说JAVA的IO包
设计模式-装饰者模式
最新推荐文章于 2018-09-05 19:15:04 发布