我有好多个好多女神,给她们过生日挑选礼物,是个难题。明天是Marry的生日了,送啥礼物喃。不想太破费,毕竟是千斤顶嘛。选一张我俩的合照,在背面写上“Marry女神,生日快乐”,再去买个相框装饰下吧,在外面再套个礼品盒,一个简单而又有心意的礼品就产生了。
不错,以上我们就是对礼物在进行装饰,同样的,对房屋等同样需要装饰,这时就需要我们的装饰模式。
装饰模式是以对客户端透明的模式扩展对象的功能,是继承关系的一个替代方案,提供比继承更多的灵活性。动态的给一个对象增加功能,增加由一些基本功能的排列组合而产生非常大量的功能。
看到这个设计模式,是在java IO中看到的,输入流和输入流,具有相当多的功能,比如处理文件、缓冲、读入和写出数据,如果使用继承的方式,会有很多的组合,就采用了装饰类,具有更大的灵活性。
WomenFace.java
package com.zy.disignpattern;
public interface WomenFace {
public void outing();
}
WomenFaceImpl.java
package com.zy.disignpattern;
public class WomenFaceImpl implements WomenFace {
@Override
public void outing() {
System.out.println("今天晚上有约会,怎么出门呢");
}
}
WomenFaceDecorator.java
package com.zy.disignpattern;
public abstract class WomenFaceDecorator implements WomenFace {
public WomenFace womenFace;
public WomenFaceDecorator(WomenFace womenFace) {
this.womenFace = womenFace;
}
@Override
public void outing() {
// TODO Auto-generated method stub
this.womenFace.outing();
}
}
NaturalWomenFaceDecorator.java
package com.zy.disignpattern;
public class NaturalWomenFaceDecorator extends WomenFaceDecorator {
public NaturalWomenFaceDecorator(WomenFace womenFace) {
super(womenFace);
}
public void outing() {
super.outing();
System.out.println("男朋友喜欢素颜,不化妆了吧");
}
}
EyeBrowWomenFaceDecorator.java
package com.zy.disignpattern;
public class EyeBrowWomenFaceDecorator extends WomenFaceDecorator {
public EyeBrowWomenFaceDecorator(WomenFace womenFace) {
super(womenFace);
}
public void outing() {
super.outing();
System.out.println("画个浓眉毛");
}
}
LipstickWomenFaceDecorator.java
package com.zy.disignpattern;
public class LipstickWomenFaceDecorator extends WomenFaceDecorator {
public LipstickWomenFaceDecorator(WomenFace womenFace) {
super(womenFace);
}
public void outing() {
super.outing();
System.out.println("画个口红");
}
}
Test.java
package com.zy.disignpattern;
public class Test {
public static void main(String[] args) {
WomenFace womenFace = new WomenFaceImpl();
womenFace.outing();
System.out.println("-----------------------");
NaturalWomenFaceDecorator womenFace1 = new NaturalWomenFaceDecorator(womenFace);
womenFace1.outing();
System.out.println("-----------------------");
EyeBrowWomenFaceDecorator womenFace2 = new EyeBrowWomenFaceDecorator(womenFace);
womenFace2.outing();
System.out.println("-----------------------");
LipstickWomenFaceDecorator womenFace3 = new LipstickWomenFaceDecorator(womenFace);
womenFace3.outing();
System.out.println("-----------------------");
EyeBrowWomenFaceDecorator womenFace4 = new EyeBrowWomenFaceDecorator(new LipstickWomenFaceDecorator(womenFace));
womenFace4.outing();
}
}
运行结果
今天晚上有约会,怎么出门呢
-----------------------
今天晚上有约会,怎么出门呢
男朋友喜欢素颜,不化妆了吧
-----------------------
今天晚上有约会,怎么出门呢
画个浓眉毛
-----------------------
今天晚上有约会,怎么出门呢
画个口红
-----------------------
今天晚上有约会,怎么出门呢
画个口红
画个浓眉毛
JAVA设计模式之 装饰模式【Decorator Pattern】
Java装饰模式
易学设计模式-郭志学编著
原文地址:http://blog.csdn.net/zy416548283/article/details/45645023