用装饰者模式展示女人的一生

1.2.4 装饰模式
      动态地给一个对象添加一些额外的职责。就增加功能来说,Decorator模式相比生成子类更为灵活。
  适用性
      1.在不影响其他对象的情况下,以动态、透明的方式给单个对象添加职责。
      2.处理那些可以撤消的职责。
      3.当不能采用生成子类的方法进行扩充时。
    参与者
      1.Component
      定义一个对象接口,可以给这些对象动态地添加职责。
      2.ConcreteComponent
      定义一个对象,可以给这个对象添加一些职责。
      3.Decorator
      维持一个指向Component对象的指针,并定义一个与Component接口一致的接口。
      4.ConcreteDecorator
      向组件添加职责。
package structural.decorator;

public interface IFemale {
    public void look();
}
package structural.decorator;

//胎儿
public class Fetus implements IFemale {

    public void look() {
        System.out.println("受孕之后,胎儿开始发育,就像一个花生那么大点.");
    }
}

package structural.decorator;

//小女孩
public class LittleGirl implements IFemale{
    Fetus fetus;
    public LittleGirl(Fetus fetus){
        this.fetus = fetus;
    }
    public void look() {
        fetus.look();
        System.out.println("出生之后,小女孩子一点点长大,天真烂漫,清纯可爱.");
    }
}

package structural.decorator;

//少女
public class Maiden implements IFemale {
    LittleGirl littleGirl;
    public Maiden(LittleGirl littleGirl){
        this.littleGirl = littleGirl;
    }
    public void look() {
        littleGirl.look();
        System.out.println("少女长大成人,楚楚动人,少女情怀总是诗.");
    }

}

package structural.decorator;

//母亲
public class Mother implements IFemale {
    Maiden maiden;
    public Mother(Maiden maiden){
        this.maiden = maiden;
    }
    public void look() {
        maiden.look();
        System.out.println("遇到喜欢的人坠入爱河,结婚生子,散发着成熟的魅力.");
    }

}
package structural.decorator;

//老妇人
public class OldLady implements IFemale {
    Mother mother;
    public OldLady(Mother mother){
        this.mother = mother;
    }
    public void look() {
        mother.look();
        System.out.println("子女渐渐长大,自己一天天老去,皱纹爬满脸庞,直至回归尘土.");
    }

}
package structural.decorator;

public class DecoratorEntry {

    public static void main(String[] args) {
        OldLady oldLady = new OldLady(new Mother(new Maiden(new LittleGirl(new Fetus()))));
        oldLady.look();
    }
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值