今天学了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*****
*/