java常用设计模式(装饰者模式)

一:装饰者设计模式(Decorator),先上代码.

抽象的组件(AbstractComponent)

public interface Animal {
	void eat();
}
具体的组件 (ConcreteComponent)
public class Dog implements Animal {

	@Override
	public void eat() {
		System.out.println("我是狗的eat(),我在吃牛肉干");		
	}

}

抽象装饰者(AbstractComponent)

public abstract class Decorator implements Animal {
	
	protected Animal animal;

	public void setAnimal(Animal animal) {
		this.animal = animal;
	}

	@Override
	public void eat() {
		System.out.println("我是装饰者实现的eat(),请开始下面的表演");
		animal.eat();
		
	}

}
测试
public class Test {
	public static void main(String[] args) {
		Animal animal = new Dog();
		Decorator decorator = new Decorator();
		decorator.setAnimal(animal);
		decorator.eat();
       }
}
//执行结果:(增加了装饰者的逻辑)
我是装饰者实现的eat(),请下开始下面的表演
我是狗的eat(),我在吃牛肉干


下面继续

具体装饰者(ConcreteDecorator)

public class DogDecoratorA extends Decorator {
	public void eat(){
		super.eat();
		System.out.println("我是DogDecoratorA");
		eatOther();
	}

	public void eatOther() {
		System.out.println("牛肉干不好吃,我要吃石头");
		
	}
}
继续测试

public class Test2 {
	public static void main(String[] args) {
		Animal animal = new Dog();
		Decorator decorator = new DogDecoratorA();
		decorator.setAnimal(animal);
		decorator.eat();
	}
}
//执行结果(dogA的装饰)
我是装饰者实现的eat(),请下开始下面的表演
我是狗的eat(),我在吃牛肉干
我是DogDecoratorA
牛肉干不好吃,我要吃石头


具体装饰者(ConcreteDecorator)

public class DogDecoratorB extends Decorator {
	public void eat(){
		super.eat();
		System.out.println("我是DogDecoratorB,我听你的吃了石头,来你过来一下");		
		
	}
}


继续测试

public class Test3 {
	public static void main(String[] args) {
		Animal animal = new Dog();
		Decorator decoratorA = new DogDecoratorA();
		Decorator decoratorB = new DogDecoratorB();
		decoratorA.setAnimal(animal);
		decoratorB.setAnimal(decoratorA);
		decoratorB.eat();
	}
}

//执行结果
我是装饰者实现的eat(),请下开始下面的表演
我是装饰者实现的eat(),请下开始下面的表演
我是狗的eat(),我在吃牛肉干
我是DogDecoratorA
牛肉干不好吃,我要吃石头
我是DogDecoratorB,我听你的吃了石头,来你过来一下
 
总结:装饰模式和继承的主要区别是:装饰模式是针对对象的,而继承是针对类的。

      由上面的代码可以看看是层层包装的,A包装了animal,B包装了A,都是调用eat方法,实现不同的功能拓展.

      可以有无数个组件层层包装.


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值