装饰着设计模式:
功能:将主功能和附加功能相分离;
好处:
1> 使主功能和附加功能可以独立扩展;
2> 降低主功能和附加功能之间的耦合性;
举例:
实现一个手机功能的接口:
package org.westos.pattern;
//规则
public interface Phone {
//电话电话的功能
public abstract void call() ;
}
创建一个类实现接口:
package org.westos.pattern;
public abstract class PhoneDecoreate implements Phone {
private Phone p ;
public PhoneDecoreate(Phone p) {
this.p = p ;
}
@Override
public void call() {
this.p.call();
}
}
实现一个类继承手机功能的类:
package org.westos.pattern;
public class RingPhoneDecorate extends PhoneDecoreate {
public RingPhoneDecorate(Phone p) {
super(p);
}
@Override
public void call() {
System.out.println("手机可以听彩铃了....");
super.call();
}
}
测试类:
package org.westos.pattern;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStreamReader;
import java.util.Scanner;
import org.westos.MusicPhoneDecorate;
//测试类
public class PhoneDemo {
public static void main(String[] args) throws FileNotFoundException {
//创建Phone对象
Phone p = new IPhone() ;
p.call();
System.out.println("-----------------");
//需求:打电话之前,先听彩铃....
PhoneDecoreate pd = new RingPhoneDecorate(p) ;
pd.call();
System.out.println("--------------------");
//需求:打完电话之后,听音乐
pd = new MusicPhoneDecorate(p) ;
pd.call();
System.out.println("---------------------");
//需求:先听彩铃,打电话--->听音乐
//装饰类
pd = new RingPhoneDecorate(new MusicPhoneDecorate(p)) ;
pd.call();
}
}