模式定义:又称为静态工厂方法模式,属于类创建型模式。
(1)抽象产品类
public interface TV{
public void play();
}
(2)具体产品类
public class HaierTV implements TV
{
public void play(){
System.out.println("海尔电视机播放中");
}
}
(3)具体产品类
public class HisenceTV implements TV
{
public void play(){
System.out.println("海信电视机播放中");
}
}
(4)工厂类
public class TVFactory
{
public static TV pruductTV(String brand) throws Exception{
if(brand.equalsIngoreCase("Haier")){
return new HaierTV();
} else if (brand.equalsIngoreCase("Haisense")){
return new HisenceTV ();}
else{
throw new Exception("对不起,不能生产该品牌电视机");
}
}
}
(5)客户端测试类
public class client{
public static void main(String [] args){
try{
TV tv;
String name="Haier";
tv=TVFactory.pruductTV(name);
tv.play();
}catch(Exception e){
System.out.println(e.getMessage()):
}
}
}