结构类模式大PK

装饰模式VS代理模式

  首先要说明的是装饰模式是代理模式的特殊应用,两者的共同点是有相同的接口,不同点事代理模式着重对代理过程的控制,而装饰模式则是对类的功能进行加强或减弱,着重类功能的变化。我们看看两者的类图吧!就是一模一样只是代理类和装饰类的名字不一样了而已。我们通过代理类和装饰类看看二者的区别吧。

设计模式之结构类模式大PK

//代理模式还是侧重于对代理过程的控制,是否允许功能的执行
public class SingerAgent{
       private Singer singer;
       public SingerAgent(Singer singer){
               this.singer = singer;
       }
       public void singing(){
               Random rand = new Random();
               if(rand.nextBoolean()){
                       System.out.println("代理人同意歌手唱歌");
                       singer.sing();
               }else{
                       System.out.println("代理人不同意歌手唱歌");
               }
       }
}
//装饰模式侧重于对装饰对象功能的增强或者减弱
public class SingerWithJet{
        private Singer singer;
        public SingerWithJet(Singer singer){
                this.singer = singer;
        }
        public void singing(){
                System.out.println("歌手的舞蹈优美");
                singer.sing();
        }
}
View Code

相关文章:

  • 2021-12-02
  • 2021-09-14
猜你喜欢
  • 2022-02-11
  • 2021-07-11
  • 2022-12-23
  • 2022-01-15
  • 2021-04-02
  • 2022-02-10
相关资源
相似解决方案