Decorator(装饰者模式)
介绍
- 装饰器模式(Decorator Pattern)允许向一个现有的对象添加新的功能,同时又不改变其结钩, 动态地给一个对象添加一些额外的职责。
- 就相当于一个 女生 给自己 化妆,戴饰品,并不会改变其本身是一个女性的特点,又修饰了自身
- 这种类型的设计模式属于结构型模式,它是作为现有的类的一个包装
优点: 装饰类和被装饰类可以独立发展,不会相互耦合,装饰模式是继承的一个替代模式,装饰模式可以动态扩展一个实现类的功能。
缺点: 多层装饰比较复杂。
注意: 可代替继承
实现

1、 创建一个接口
public interface Clothes {
void wear();
}
2、 创建实现接口的实体类
public class Hat implements Clothes{
@Override
public void wear() {
System.out.println("戴着帽子....");
}
}
public class Jacket implements Clothes{
@Override
public void wear() {
System.out.println("穿着夹克.....");
}
}
3、 创建实现了 Clothes 接口的抽象装饰类
public abstract class ClothesDecorator implements Clothes {
protected Clothes clothes;
public ClothesDecorator(Clothes clothes) {
this.clothes = clothes;
}
@Override
public void wear() {
clothes.wear();
}
}
4、 创建扩展了 ClothesDecorator 类的实体装饰类
public class RedClothesDecorator extends ClothesDecorator{
public RedClothesDecorator(Clothes clothes) {
super(clothes);
}
@Override
public void wear() {
super.wear();
clothesColor(clothes);
}
private void clothesColor(Clothes clothes) {
System.out.println(clothes.toString() + "是绿色的...");
}
}
5、 使用 RedClothesDecorator 来装饰 Shape 对象
public class DecoratorDemo {
public static void main(String[] args) {
RedClothesDecorator redClothesDecorator = new RedClothesDecorator(new Hat());
redClothesDecorator.wear();
RedClothesDecorator jacketClothesDecorator = new RedClothesDecorator(new Jacket());
jacketClothesDecorator.wear();
}
}
装饰器模式是一种结构型设计模式,它允许向已有对象添加新功能而不修改其内部代码。通过创建包装器对象,我们可以动态地给对象增加职责。这种模式在Java和Python等语言中常见,作为继承的替代方案,减少了类的数量并保持了对象的独立性。在示例中,Clothes接口和其实现类展示了如何创建装饰者模式的基础结构,而ClothesDecorator抽象类及RedClothesDecorator实体装饰类则展示了如何扩展功能。这种模式的优点在于装饰类和被装饰类可以独立演进,但缺点是多层装饰可能导致复杂性增加。
1234

被折叠的 条评论
为什么被折叠?



