当前位置:网站首页>Decorator (2)

Decorator (2)

2020-11-08 21:03:00 8Years

//
//     Simulation coffee 
//    1. Abstract components : Abstract objects that need decoration ( Interface or abstract parent class )
//    2. Specific components : Objects that need decoration 
//    3. Abstract decorator : Contains references to abstract components and decorates common methods 
//    4. Concrete decoration : Objects to be decorated 


public class TestDecoretorTwo {


    public static void main(String[] args) {
        Drink coffee = new coffee();
        Drink suger = new Suger(coffee);
        System.out.println(suger.cost() + "--->" + suger.Info());
        Drink milk = new Milk(coffee);
        System.out.println(milk.cost() + "--->" + milk.Info());


        Drink milk1 = new Milk(suger);
        System.out.println(milk1.cost() + "--->" + milk1.Info());

    }

}


    //    1. Abstract components 
    interface Drink{
    int cost();
    String Info();
    }

     //    2. Specific components :
     class coffee implements Drink{

        String name=" Original coffee ";
        public int cost() {
            return 10;
        }

        @Override
        public String Info() {
            return name;
        }
    }


    //    3. Abstract decorator :
    class Decorate implements Drink{
        // References to abstract components 

        private Drink drink;


        public Decorate(Drink drink) {
            // Here's a constructor (this

            this.drink = drink;
        }

        @Override
        public int cost() {
            return this.drink.cost();
        }

        @Override
        public String Info() {
            return this.drink.Info();
        }
    }
    //    4. Concrete decoration 1
     class Milk extends Decorate{

        public Milk(Drink drink) {
            // Here's a constructor ,(super
            super(drink);
        }

        @Override
        public int cost() {
            return super.cost()*4;
        }

        @Override
        public String Info() {
            return super.Info()+" With milk ";
        }
    }

    //    4. Concrete decoration 2
    class Suger extends Decorate{
        public Suger(Drink drink) {
            super(drink);
        }

        @Override
        public int cost() {
            return super.cost()*2;
        }

        @Override
        public String Info() {
            return super.Info()+" Added sugar ";
        }
    }

 

Output results

20---> Original coffee with sugar
40---> Original coffee with milk
80---> Original coffee with sugar and milk

版权声明
本文为[8Years]所创,转载请带上原文链接,感谢