多态及装饰者模式辨析
装饰者模式代码如下:
public class Coffee{
public void drink(){
System.out.println("drink coffee");
}
}
public abstract class CoffeeDecorator extends Coffee{
protected Coffee coffee;
public CoffeeDecorator(Coffee coffee){
this.coffee = coffee;
}
public void drink(){
coffee.drink();
}
}
public class Latte extends CoffeeDecorator {
public Latte(Coffee coffee) {
super(coffee);
}
void addSomething() {
System.out.println("add some milk");
}
public void drink(){
this.addSomething();
super.drink();
}
}
public class Mocha extends CoffeeDecorator{
public Mocha(Coffee coffee) {
super(coffee);
}
void addSomething() {
System.out.println("add some chocolates");
}
public void drink(){
addSomething();
super.drink();
}
}
public class Person {
public static void main(String[] args) {
Coffee coffee = new Coffee();
CoffeeDecorator latte = new Latte(new Mocha(coffee));
latte.drink();
}
}
///:输出结果
add some milk
add some chocolates
drink coffee
错误代码:
public class Coffee{
public void drink(){
System.out.println("drink coffee");
}
}
public abstract class CoffeeDecorator extends Coffee{
protected Coffee coffee;
public CoffeeDecorator(Coffee coffee){
this.coffee = coffee;
}
public void drinkcoffee(){
coffee.drink();
}
}
public class Latte extends CoffeeDecorator {
public Latte(Coffee coffee) {
super(coffee);
}
void addSomething() {
System.out.println("add some milk");
}
public void drinkcoffee(){
this.addSomething();
super.drinkcoffee();
}
}
public class Mocha extends CoffeeDecorator{
public Mocha(Coffee coffee) {
super(coffee);
}
void addSomething() {
System.out.println("add some chocolates");
}
public void drinkcoffee(){
addSomething();
super.drinkcoffee();
}
}
public class Person {
public static void main(String[] args) {
Coffee coffee = new Coffee();
CoffeeDecorator latte = new Latte(new Mocha(coffee));
latte.drinkcoffee();
}
}
///:输出结果
add some milk
drink coffee
错误原因:
Latte的super.drinkcoffee();会走到coffee.drink(),虽然Mocha也是Coffee,但是Mocha没有drink方法,不会向下绑定到Mocha,直接走了CoffeeDecorator的drinkcoffee方法
装饰着模式的原因:
因为动态绑定的机制,会自动执行子类的方法,所以同样的调用会不停调用每个实现类的相同方法,以此实现装饰