想成为高级Android工程师其中熟悉常见的设计模式是必不可少的,这个也是我面试一线互联网公司的深刻体会,首先我们现在介绍最基础也是最常用的设计模式:装饰模式
动态地给一个对象添加一些额外的职责。就增加功能来说, Decorator模式相比生成子类更为灵活。该模式以对客 户端透明的方式扩展对象的功能。
装饰模式是一种动态行为,对已经存在类进行随意组合,而类的继承是一种静态的行为,一个类定义成什么样的,该类的对象便具有什么样的功能,无法动态的改变。
一、装饰模式组成
抽象组件:定义一个抽象接口,来规范准备附加功能的类
具体组件:将要被附加功能的类,实现抽象构件角色接口
抽象装饰者:持有对具体构件角色的引用并定义与抽象构件角色一致的接口
具体装饰:实现抽象装饰者角色,负责对具体构件添加额外功能。
二、业务实现
//业务接口
public interface Person {
void eat();
}
//具体业务实现
public class Man implements Person {
public void eat() {
System.out.println("男人在吃");
}
}
三、装饰类实现
//装饰类一定要实现业务接口
public abstract class Decorator implements Person {
protected Person person;
public void setPerson(Person person) {
this.person = person;
}
public void eat() {
person.eat();
}
}
//具体装饰类A
public class ManDecoratorA extends Decorator {
public void eat() {
super.eat();
reEat();
System.out.println("ManDecoratorA类");
}
public void reEat() {
System.out.println("再吃一顿饭");
}
}
//具体装饰类B
public class ManDecoratorB extends Decorator {
public void eat() {
super.eat();
System.out.println("===============");
System.out.println("ManDecoratorB类");
}
}
四、测试模块
public class Test {
public static void main(String[] args) {
Man man = new Man();
ManDecoratorA md1 = new ManDecoratorA();
ManDecoratorB md2 = new ManDecoratorB();
md1.setPerson(man);
md2.setPerson(md1);
md2.eat();
}
}
五、总结
OO原则:动态地将责任附加到对象上。想要扩展功能, 装饰者提供有别于继承的另一种选择。
1、继承属于扩展形式之一,但不见得是达到弹性设计的最佳方案。
2、在我们的设计中,应该允许行为可以被扩展,而不须修改现有的代码。
3、除了继承,装饰者模式也可以让我们扩展行为。
4、装饰者可以在被装饰者的行为前面与/或后面加上自己的行为,甚至将被装饰者的行为整个取代掉,而达到特定的目的。
资料引用 https://www.cnblogs.com/chenxing818/p/4705919.html