装饰模式
给对象添加新的功能。
·确定被修饰的抽象事物是谁?
·具体的被修饰事物;
·对被修饰事物装饰的抽象类-----对被修饰事物的接口进行继承
·对被修饰事物进行具体修饰的类。
/**
* 手机接口* @author lcj
*/
public interface Phone {
public abstract void call();
}
/**
* 手机实现类
* @author lcj
*/
public class PhoneImpl implements Phone{
@Override
public void call() {
System.out.println("手机可以打电话");
}
}
/**
* 用于装饰手机的抽象类
* @author lcj
*/
public abstract class PhoneDecorate implements Phone{
private Phone phone;
public PhoneDecorate(Phone phone){
this.phone = phone;
}
@Override
public void call() {
this.phone.call();
}
}
/**
* 添加彩铃功能---进行装饰手机
* @author lcj
*/
public class ColorDecorate extends PhoneDecorate{
public ColorDecorate(Phone phone) {
super(phone);
}
@Override
public void call() {
System.out.println("手机可以播放彩铃");
super.call();
}
}
/**
* 添加播放音乐功能进行装饰手机
* @author lcj
*/
public class MusicDecorate extends PhoneDecorate{
public MusicDecorate(Phone phone) {
super(phone);
}
@Override
public void call() {
System.out.println("手机可以播放音乐");
super.call();
}
}
/**
* 测试类
* @author lcj
*/
public class PhoneTest {
public static void main(String[] args) {
Phone phone = new PhoneImpl();
phone.call();
System.out.println("***************************");
PhoneDecorate color = new ColorDecorate(phone);
color.call();
System.out.println("***************************");
PhoneDecorate music = new MusicDecorate(phone);
music.call();
System.out.println("***************************");
PhoneDecorate colorAndMusic = new ColorDecorate(
new MusicDecorate(phone));
colorAndMusic.call();
System.out.println("***************************");
}
}
举例:
java中javaio流体现了装饰模式:
BufferedInputStream
BufferedOutputStream
BufferedReader
BufferedWriter
writer
|--OutputStreamWriter
|--FileWriter
|--BufferedWriter
Bufferedxxx其实是对io流进行了缓冲处理,为了提高效率。
new BufferedWriter(new FileWriter("a.txt"));