您的位置:首页 > 其它

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

2012-03-29 15:57 267 查看
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();
}
}


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息