Decorator和Factory设计模式的混搭

今天学了Decorator设计模式,但是main函数内太过复杂,突然想到了前几天学的Factory设计模式,因此尝试组合在一起看看效果如何。在Factory –条件语句if里面有一些重复代码,请问怎么处理。请多指教。

interface Product{
    public void productName();
}

class TV implements Product{
    public void productName(){
        System.out.println("cctv-5 NBA");
    }
}

class Washer implements Product{
    public void productName(){
        System.out.println("wash cloth....");
    }
}

class TCL implements Product{
    private Product product;
    public TCL(Product product){
        this.product = product;
    }
    public void productName(){
        product.productName();
        System.out.println("****produced by TCL corporation*****");
    }
}

class Factory{
    public static Product getInstance(String company,String product){
        if(company.equals("TCL") && product.equals("TV")){
            Product tv = new TV();
            TCL tclProduct = new TCL(tv);
            tclProduct.productName();
            return tclProduct;
        }else if(company.equals("TCL") && product.equals("Washer")){
            Product washer = new Washer();
            TCL tclProduct = new TCL(washer);
            tclProduct.productName();
            return tclProduct;
        }else{
            return null;
        }
    }
}

public class TestDemo{
    public static void main(String args[]){
        Factory pd = new Factory();
        pd.getInstance("TCL","TV");
        pd.getInstance("TCL","Washer");
    }
}
/*Output
cctv-5 NBA
****produced by TCL corporation*****
wash cloth....
****produced by TCL corporation*****
*/
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值