Java设计模式之桥梁模式

桥梁模式特点在于,多个维度都可自由扩展,而继承只能向一个维度扩展。
代码来自《您的设计模式》


package com.pocketdigi.patterns.bridge;

public abstract class Product {
    public abstract void beProducted();
    public abstract void beSelled();
}

package com.pocketdigi.patterns.bridge;
/**
 * 可根据需求扩展crop类
 */
public class HouseCrop extends Crop {
    /**
     * 只能生产House,所以参数为House,不是Product
     * @param product
     */
    public HouseCrop(House product) {
        super(product);
        // TODO Auto-generated constructor stub
    }
    @Override
    public void makeMoney() {
        // TODO Auto-generated method stub
        super.makeMoney();
        System.out.println("房地产公司赚大钱了...");
    }

}

package com.pocketdigi.patterns.bridge;
/**
 * 扩展Crop
 */
public class ShanZhaiCrop extends Crop {

    /**
     * 根据传入的Product不同,生产出不同的产品
     * @param product
     */
    public ShanZhaiCrop(Product product) {
        super(product);
        // TODO Auto-generated constructor stub
    }
    @Override
    public void makeMoney() {
        // TODO Auto-generated method stub
        super.makeMoney();
        System.out.println("我赚钱啦...");
    }

}

package com.pocketdigi.patterns.bridge;
/**
 * 产品,也可以根据需求自由扩展
 */
public abstract class Product {
    public abstract void beProducted();
    public abstract void beSelled();
}

package com.pocketdigi.patterns.bridge;

public class House extends Product {

    @Override
    public void beProducted() {
        // TODO Auto-generated method stub
        System.out.println("生产出的房子是这样的...");
    }

    @Override
    public void beSelled() {
        // TODO Auto-generated method stub
        System.out.println("生产出的房子卖出去了...");
    }

}

package com.pocketdigi.patterns.bridge;

public class Clothes extends Product {

    @Override
    public void beProducted() {
        // TODO Auto-generated method stub
        System.out.println("生产出的衣服是这样的...");
    }

    @Override
    public void beSelled() {
        // TODO Auto-generated method stub
        System.out.println("生产出的衣服卖出去了...");
    }

}


package com.pocketdigi.patterns.bridge;

public class IPod extends Product{

    @Override
    public void beProducted() {
        // TODO Auto-generated method stub
        System.out.println("生产出的IPod是这样的...");
    }

    @Override
    public void beSelled() {
        // TODO Auto-generated method stub
        System.out.println("生产出的IPod卖出去了...");
    }

}

使用:


        //桥梁模式
        Crop crop1=new HouseCrop(new House());
        crop1.makeMoney();
        
        Crop crop2=new ShanZhaiCrop(new Clothes());
        crop2.makeMoney();
        
        Crop crop3=new ShanZhaiCrop(new IPod());
        crop3.makeMoney();

© 2014, 冰冻鱼. 请尊重作者劳动成果,复制转载保留本站链接! 应用开发笔记

发表评论

电子邮件地址不会被公开。 必填项已用*标注