public class Client {
public static void main(String[] args){
try{
String brandName = "Haier";
TV tv = TVFactory.produceTV(brandName);
tv.play();
}catch (Exception e){
System.out.println(e.getMessage());
}
}
}
public class TVFactory {
public static TV produceTV(String brand) throws Exception {
if (brand.equalsIgnoreCase("Hair")) {
System.out.println("电视机工厂生产海尔电视");
return new HairTV();
} else if (brand.equalsIgnoreCase("Hisense")) {
System.out.println("电视机工厂生产海信电视");
return new HisenseTV();
}else {
throw new Exception("对不起,暂无该品牌电视机");
}
return new HairTV();
}
}
public interface TV {
void play();
}
public class HairTV implements TV {
public void play(){
System.out.println("海尔电视播放中。。。。");
}
}
public class HisenseTV implements TV{
public void play(){
System.out.println("海信电视播放中。。。。。");
}
}
缺点:当增加功能模块,不仅要添加新的功能模块,而且要修改TVFactory
类中的代码,这违反了开闭原则。