装饰器模式的应用场景:
1、需要扩展一个类的功能。
2、动态的为一个对象增加功能,而且还能动态撤销。(继承不能做到这一点,继承的功能是静态的,不能动态增删。)
package study.org;
public class Demo {
public static void main(String[] args) {
Product product = new ProductImpl(1);
Decorator add1 = new Add1(product);
Decorator add2 = new Add2(add1);
System.out.println(add2.showPrice());
}
}
interface Product {
int showPrice();
}
class ProductImpl implements Product {
private int price;
public ProductImpl(int price) {
super();
this.price = price;
}
@Override
public int showPrice() {
return price;
}
}
// 装饰模式
abstract class Decorator implements Product {
private Product product;
public Decorator(Product product) {
super();
this.product = product;
}
@Override
public int showPrice() {
return product.showPrice();
}
}
// 装饰类1
class Add1 extends Decorator {
public Add1(Product product) {
super(product);
}
@Override
public int showPrice() {
return 1 + super.showPrice();
}
}
// 装饰类2
class Add2 extends Decorator {
public Add2(Product product) {
super(product);
}
@Override
public int showPrice() {
return 2 + super.showPrice();
}
}
网友评论