装饰器模式:
装饰器模式就是将其拆分成单独的装饰器类,这些装饰器类组合起来达到应用者想要目的的一种手段。其本质就是动态组合。
举个简单的例子,去手机专卖店买了一部小米手机,与售货员谈条件最后购买了小米手机的同时还附赠了小米耳机和小米充电器,在这里你主要需要的只是小米手机,而其他零件只起到装饰小米手机的作用。它们的关系如下图所示:
通过代码进行详细阐述:
XIAOMICompany.java
//01通用父类:小米公司
public abstract class XIAOMICompany {
//只需包含显示信息即可,因为不需要写方法体,所以采用抽象类定义抽象方法
public abstract void showInfo();
}
XIAOMIPhone.java
//02小米手机(被装饰者类)
public class XIAOMIPhone extends XIAOMICompany{
//继承小米公司,因为是小米公司的产品,
//抽象类可以作为父类,但是子类会报错,原因是,能继承抽象方法。
//解决方案:
//1.将子类也定义成抽象类
//2.重写抽象类中所有的抽象方法,如果不重写或者只重写部分抽象方法,那么代码还会报错
//所以本例中我们重写父类显示信息的方法
@Override
public void showInfo() {
System.out.print("我是一个小米手机");
}
}
XIAOMIParts.java
//03装饰者父类(装饰对象的总体)
public abstract class XIAOMIParts extends XIAOMICompany{
XIAOMICompany xiaomiCompany;
//构造方法
public XIAOMIParts(XIAOMICompany xiaomiCompany) {
this.xiaomiCompany = xiaomiCompany;
}
}
XIAOMICharger.java
//04小米充电器
public class XIAOMICharger extends XIAOMIParts{
public XIAOMICharger(XIAOMICompany xiaomiCompany) {
super(xiaomiCompany);
}
@Override
public void showInfo() {
xiaomiCompany.showInfo();
System.out.print("添加了小米手机充电器");
}
}
XIAOMIEEar.java
//05小米耳机
public class XIAOMIEEar extends XIAOMIParts{
public XIAOMIEEar(XIAOMICompany xiaomiCompany) {
super(xiaomiCompany);
}
@Override
public void showInfo() {
xiaomiCompany.showInfo();
System.out.print("添加了小米耳机");
}
}
Test.java
//06测试类
import ZSQ.zsq.XIAOMIPhone;
public class Test {
public static void main(String[] args) {
XIAOMIPhone xiaomiPhone = new XIAOMIPhone();
xiaomiPhone.showInfo();
System.out.println();
}
}
//06测试类
import ZSQ.zsq.XIAOMICharger;
import ZSQ.zsq.XIAOMIEEar;
import ZSQ.zsq.XIAOMIPhone;
public class Test {
public static void main(String[] args) {
XIAOMIPhone xiaomiPhone = new XIAOMIPhone();
xiaomiPhone.showInfo();
System.out.println();
//对象传递的是小米手机,所以结果是在小米手机上添加了小米充电器
XIAOMICharger xiaomiCharger = new XIAOMICharger(xiaomiPhone);
xiaomiCharger.showInfo();
System.out.println();
//对象传递的是小米手机,所以结果是在小米手机上添加了小米耳机
XIAOMIEEar xiaomieEar = new XIAOMIEEar(xiaomiPhone);
xiaomieEar.showInfo();
System.out.println();
}
}
//06测试类
import ZSQ.zsq.XIAOMICharger;
import ZSQ.zsq.XIAOMIEEar;
import ZSQ.zsq.XIAOMIPhone;
public class Test {
public static void main(String[] args) {
XIAOMIPhone xiaomiPhone = new XIAOMIPhone();
xiaomiPhone.showInfo();
System.out.println();
//此时是在小米手机上添加了小米充电器
XIAOMICharger xiaomiCharger = new XIAOMICharger(xiaomiPhone);
xiaomiCharger.showInfo();
System.out.println();
//此时传递的对象是已经添加了小米充电器的小米手机,
//所以结果会是在已经添加了小米充电器的手机的基础上再添加小米耳机
XIAOMIEEar xiaomieEar = new XIAOMIEEar(xiaomiCharger);
xiaomieEar.showInfo();
System.out.println();
}
}
你看懂了吗?