设计模式(第七式:装饰模式)

概念:
  装饰模式:动态的为一些对象添加一些职责。即就是动态的为一些对象添加一些方法。

实现:
  定义作者接口

public interface Author {
        /**
         * 作家具有写作的能力
         */
        void write();

        /**
         * 作家都给自己写的书上签名
         */
        void sign();
    }


  小说作家类

    public class NovelAuthor implements Author {

        @Override
        public void write() {
            System.out.println("我是小说家,就写个小说吧");
        }

        @Override
        public void sign() {
            System.out.println("这本书要买了,我要签名后才可以");
        }
    }


  装饰者接口

    public abstract class Decorator implements Author {
        private Author author = null;
        public Decorator(Author author){
            this.author = author;
        }

        @Override
        public void write() {
            this.author.write();
        }

        @Override
        public void sign() {
            this.author.sign();
        }
    }


  小说装饰者

    public class AuthorDecorator extends Decorator {
        public AuthorDecorator(Author author) {
            super(author);
        }

        /**
         * 我可能还需要喝点酒
         */
        private void drink(){
            System.out.println("我要喝两杯");
        }

        @Override
        public void write() {
            this.drink();
            super.write();
        }

        @Override
        public void sign() {
            this.drink();
            super.sign();
        }
    }


分析:
  1.有没有一种感觉,这玩意儿和静态代理没啥区别啊。其实差别是不大,都是为了添加职责,但有一种场景会将你分清楚两者的区别,也算是这两者的本质区别。如果一个具体的类的对象还不存在,我们想要用到它的一写方法,并且它的方法不足以满足我们的需求,我们还需要再改一些,这个时候使用代理模式。另外一种场景,某个累类的对象已经存在了,我们想用它身上的某行方法,但是发现,他的方法不完善,我们需要再改一改,则使用装饰模式。也就是说代理模式会帮我们创建一个被代理对象,但是装饰模式前提是我们必须有一个对象,他才能帮我们装饰。
  2.适用场景:
    a.对一些框架的二次封装
    b.对servlet的封装
    ...

经典框架中使用的:
    Spring中,Httpclient等

猜你喜欢

转载自www.cnblogs.com/ben-mario/p/10710385.html