JAVA初级设计模式-------装饰模式

95 阅读2分钟
原文链接: www.shsxt.com
装饰模式的优势:
1.不改变原有文件和使用继承
2.扩展对象的功能是 动态的,比继承有更多的灵活性
3. file:///C:/Users/ADMINI~1/AppData/Local/Temp/msohtmlclip1/01/clip_image002.png 把类的核心功能和装饰功能区分开。
4. 通过使用不同的具体装饰类以及这些装饰类的排列组合,可创造出很多不同行为的组合。
设计模式涉及到的角色有: 抽象的主体(被装饰的类)、具体的主体、抽象的装饰类和具体的装饰类。


举例子:做蛋糕;
/*抽象的主体*/
public abstract class Cake {
        public void make(){
                System.out.println("一个蛋糕。");
        }
}
/*具体的主体*/
public class ChocolateCake extends Cake {
        @Override
        public void make() {
                System.out.println("一个巧克力蛋糕");
        }
}

/*抽象类的装饰类*/
public abstract class DecoratorCake extends Cake {
        private Cake cake;
        public DecoratorCake() {
                // TODO Auto-generated constructor stub
        }
                public DecoratorCake(Cake cake) {
                super();
                this.cake = cake;
        }
        @Override
        public void make() {
                cake.make();
        }
}

/*具体的装饰类*/
public class FlowerDecaratorCake extends DecoratorCake {
        public FlowerDecaratorCake() {
                // TODO Auto-generated constructor stub
        }
        public FlowerDecaratorCake(Cake cake) {
                super(cake);
        }
        @Override
        public void make() {
                super.make();
                System.out.println("加装饰:一朵鲜花");
        }
}

public class IceCreamCake extends Cake {
        @Override
        public void make() {
                System.out.println("一个冰淇淋蛋糕");
        }
}

public class NutDecaratorCake extends DecoratorCake {
        public NutDecaratorCake() {
                // TODO Auto-generated constructor stub
        }
        public NutDecaratorCake(Cake cake) {
                super(cake);
        }
        @Override
        public void make() {
                super.make();
                System.out.println("加装饰:加杏仁,腰果,榛果。");
        }
}

/*测试类*/

public class Test {
        public static void main(String[] args) {
                /*Cake cake=new CreamCake();//奶油蛋糕;
                cake=new NutDecaratorCake(cake);
                cake=new CardDecaratorCake(cake);
                cake=new FlowerDecaratorCake(cake);
                cake.make();*/
                
                Cake cake=new NutDecaratorCake(new CardDecaratorCake(new FlowerDecaratorCake(new ChocolateCake()))) ;
               cake.make();
                  
        }

}