您的位置:首页 > 职场人生

《黑马程序员》java之装饰设计模式

2013-11-22 21:01 363 查看
 ----------- android培训java培训、java学习型技术博客、期待与您交流! ------------

装饰设计模式概述

        动态地给一个对象添加一些额外的职责。就增加功能来装饰器比生成子类更为灵活

      一般 有两种方式可以实现给一个类或对象增加功能

           继承机制,使用继承机制是给现有类添加功能的一种有效途径,通过继承一个先有了可以使得子类子在拥有自身方法的同时还拥有父类的方法,但是这种方法是静态的,用户不能控制增加行为的方式和时机

          关联机制,即将一个雷的对象嵌入别一个对象中,有别一个对象来决定是否调用嵌入对象的行为以便扩展自己的行为,我们成为这个嵌入的对象为装饰器(Decorator)

            

    实例1 

           当想要对自己已有的对象增强功能时,定义类,将已有对象传入,基于已有功能,加强功能,自定义的这个类称为装饰类,通常会利用构造方法接收被装饰的对象

           

package Io;
class Person

{
public void chifan()
{
System.out.println("吃饭");
}
}
class SuperPerson//装饰类
{
private Person p;//被装饰的对象
SuperPerson(Person p)//构造时,传入对象
{
this.p=p;
}
public void superChifan()

{
System.out.println("开胃菜");
System.out.println("甜点");
System.out.println("来一桶");
p.chifan();
}
}

public class Zs {

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
SuperPerson sp=new SuperPerson(new Person());
sp.superChifan();
}

}
 实例2 

        1.定义个对象接口,可以给这些对象动态的添加职责(compent)

        2.定义个对象,可以给这个对象添加一些职责(COncreteCompoent)

        3.维持一个指向Compoent对象的指针,并定义一个与Compoent接口一致的接口

        4.向组件添加职责

package IO流;
interface Person{//COmponent
void eat();
}
class Man implements Person{

@Override
public void eat() {
// TODO Auto-generated method stub
System.out.println("man在吃");
}

}
abstract class Decorator implements Person{
protected Person person;
public void setPerson(Person person)
{
this.person=person;
}
public void eat()
{
person.eat();

}
}
class ManDecoratorA extends Decorator{
public void eat(){
super.eat();
reEat();
System.out.println("DecoratorA");
}
public  void reEat(){
System.out.println("manA再吃一顿饭");
}
}
class ManDecoratorB extends Decorator{
public void eat(){
super.eat();

System.out.println("==========DecoratorB");
}

}

public class Test {

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Man man=new Man();
ManDecoratorA ma=new ManDecoratorA();
ManDecoratorB mb=new ManDecoratorB();
// mb.setPerson(man);
//  ma.setPerson(mb);
ma.setPerson(man);//  定义个对象,可以给这个对象添加一些职责  COncreteCompoent
mb.setPerson(ma); //  向组件添加职责
mb.eat();
}

}

    这个职责的的添加可以任意,ma添加man,mb添加man,ma添加mb,mb添加ma,所以这种方法的灵活性很高,但是又比较臃肿

    

   装饰模式的优点

                装饰模式与继承关系的目的都是要扩展对象的功能,但是装饰模式可以提供比继承更多的灵活性。

                可以通过一种动态的方式来扩展一个对象的功能,通过配置文件可以在运行时选择不同的装饰器,从而实现不同的行为。

                通过使用不同的具体装饰类以及这些装饰类的排列组合,可以创造出很多不同行为的组合。可以使用多个具体装饰类来装饰同一对象,得到功能更为强大的对象。

                具体构件类与具体装饰类可以独立变化,用户可以根据需要增加新的具体构件类和具体装饰类,在使用时再对其进行组合,原有代码无须改变,符合“开闭原则

      
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: