java性能优化读书笔记之二《设计优化===装饰者模式》

1. 目的

动态的给对象添加功能,以达到松散耦合的目的。

2. 什么是装饰者

动态的给对象添加功能,并且不影响其对象结构

3. 解决什么问题

1、继承是属于紧密耦合,不便于系统架构扩展
2、解决子类膨胀

4. 如何解决

将具体功能职责划分,同时继承装饰者模式。

5. 好处

不需要修改被装饰类的任何地方,通过装饰类可以动态的添加对象的功能。以达到解耦的目的

6. 坏处

业务逻辑更加的复杂

7. 角色分配
角色作用
组件接口组件接口是装饰者和被装饰者额超类
具体组件具体组件实现了组件接口的核心方法,完成某一个具体的业务逻辑
装饰者实现组件接口,并持有一个具体的被装饰者对象
具体装饰者具体的装饰者业务逻辑,即实现了被分离的各个增强的功能点。
8. 业务场景
/**
 * 业务场景:基类动物(animal),具有吃的功能(eat方法),子类有猫(cat)、狗(dog)。都是实现了吃的功能。
 *          现在需要增加动物跑的功能(run)功能。按照继承的原则,需要在基类动物(animal)增加跑的功能(run方法)。同时
 *         子类都需要修改。
 * 解决方法:使用装饰者模式
 * @author Administrator
 *
 */
9. 代码清单
package com.one.design;



public class Decorator {

}

/**
 * 组件接口:动物
 * @author Administrator
 *
 */
interface Animal{

    /**
     * 吃的功能
     */
    public void eat();

}

/**
 * 组件实现类接口:猫
 * @author Administrator
 *
 */
class Cat implements Animal{

    /**
     * 吃的功能
     */
    public void eat() {
        System.out.println("Cat eat food");
    }

}



/**
 * 组件实现类接口:狗
 * @author Administrator
 *
 */
class Dog implements Animal{

    /**
     * 吃的功能
     */
    public void eat() {
        System.out.println("Dog eat food");
    }

}


abstract class AnimalDecorator implements Animal{

    public Animal animal;

    public AnimalDecorator(Animal animal) {
        this.animal = animal;
    }



}

class Run extends AnimalDecorator{

    public Run(Animal animal) {
        super(animal);
    }

    /**
     * 吃的功能
     */
    public void eat() {
        animal.eat();
        run(animal);
    }

    public void run(Animal animal) {
        System.out.println(animal+"run");
    }

}

class Test {
    public static void main(String[] args) {
        Animal animal = new Run(new Cat() );

        animal.eat();

        Animal animal2 = new Run(new Dog() );

        animal2.eat();

    }
 }




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值