设计模式-装饰者模式

  1. 装饰者模式
    利用继承和组合的方式实现给一个类添加不同功能
    例子:
    需求:手机为父类,子类有小米、华为,给他们装饰内存卡、充电宝等小类
    手机父类:
    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包



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值