編寫一個簡單工廠模式的程序
public interface clothingType {
public void getType(); //打印選擇的服裝類型
}
public class t_shirt implements clothingType{
@Override
public void getType() {
System.out.println("您選擇的是T恤");
}
}
public class short_sleeve implements clothingType{
@Override
public void getType() {
System.out.println("您選擇的是短袖");
}
}
public class clothingFactory {
public static clothingType CreateType(String type)
//根據提供的類型,去實例化具體的對象
{
clothingType ctype = null;
switch (type)
{
case"T恤":
ctype = new t_shirt(); //如果是T恤,則返回T恤子類
break;
case"短袖":
ctype = new short_sleeve(); //如果是短袖,則返回短袖子類
break;
}
return ctype;
}
}
public class 服裝廠 {
public static void main(String[] args) {
clothingType type1 = clothingFactory.CreateType("T恤");
//傳入參數“T恤”,讓工廠去實例化對象的T恤類
type1.getType();
clothingType type2 = clothingFactory.CreateType("短袖");
//傳入參數“短袖”,讓工廠去實例化對象的短袖類
type2.getType();
}
}
運行結果: