Kotlin设计模式.Java的装饰器模式在kotlin的实现
装饰器模式
Java
/**
* 抽象组件
* /
public interface Animal{
void eat();
}
/**
* 被装饰者
* /
public class Panda implements Animal{
@Override
public void eat(){
System.out.println("什么都没有, 不知道吃什么")
}
}
/**
* 装饰者组件
* /
public abstract class Food implements Animal{
Animal animal;
public Food(Animal animal){
this.animal = animal;
}
}
/**
* 具体装饰1
* /
public class BambooFood extends Food{
public BambooFood(Animal animal){
super(animal);
}
@Override
public void eat(){
super.eat();
System.out.println("可以吃竹子");
}
}
/**
* 具体装饰2
* /
public class CarrotFood extends Food {
public CarrotFood(Animal animal){
super(animal);
}
@Override
public void eat(){
super.eat();
System.out.println("可以吃胡萝卜");
}
}
public class Test{
public static void main(String[] args){
//创建被装饰者
Panda panda = new Panda();
//熊猫被装饰了竹子, 可以吃竹子
BambooFood bambooFood = new BambooFood(panda);
//可以吃竹子的熊猫, 被装饰了胡萝卜, 可以吃胡萝卜了
CarrotFood carrotFood = new CarrotFood(bambooFood);
carrotFood.eat();
}
}
kotlin
fun Panda.bamboo(decorator: ()->Unit){
eat()
parintln("可以吃竹子")
decorator()
}
fun Panda.carrot(decorator: ()->Unit){
parintln("可以吃胡萝卜")
decorator()
}
fun main(){
Panda().run{
bamboo{
carrot{}
}
}
}