以下以例子来总结几种工厂模式,如有需要,请花点时间耐心阅读,谢谢。
3. 抽象工厂模式
场景假设:小明同学打算买一部手机,但是现在市面上的手机品牌大致分为两种:苹果手机和华为手机,对应的操作系统为苹果系统和安卓系统,现在需要设计一种模式,让客户选择手机品牌,自动对应于操作系统。
interface Phone {
void printPhone();
}
public class Iphone implements Phone {
public void printPhone() {
System.out.println("苹果手机");
}
}
public class HuaWei implements Phone {
public void printPhone() {
System.out.println("华为手机");
}
}
interface OperatingSystem {
void printSystem();
}
public class IphoneSystem implements OperatingSystem {
public void printSystem() {
System.out.println("IOS系统");
}
}
public class AndroidSystem implements OperatingSystem {
public void printSystem() {
System.out.println("安卓系统");
}
}
interface PhoneFactory {
Phone createPhone();
OperatingSystem createSystem();
}
public class IphoneFactory implements PhoneFactory {
public Phone createPhone() {
return new Iphone();
}
public OperatingSystem createSystem() {
return new IphoneSystem();
}
}
public class HuaWeiFactory implements PhoneFactory {
public Phone createPhone() {
return new HuaWei();
}
public OperatingSystem createSystem() {
return new AndroidSystem();
}
}
public class Client {
public void buyPhone(Phone phone) {
phone.printPhone();
}
public void use(OperatingSystem operatingSystem) {
operatingSystem.printSystem();
}
public Phone select(String str) {
if(str.equals("苹果")) {
return new Iphone();
}else {
return new HuaWei();
}
}
//上一段方法可写成
// public Phone select(String str) {
// if(str.equals("苹果")) {
// return new IphoneFactory().createPhone();
// }else {
// return new HuaWeiFactory().createPhone();
// }
// }
public OperatingSystem selectSystem(String str) {
if(str.equals("苹果")) {
return new IphoneSystem();
}else {
return new AndroidSystem();
}
}
//上一段方法可写成
// public OperatingSystem selectSystem(String str) {
// if(str.equals("苹果")) {
// return new IphoneFactory().createSystem();
// }else {
// return new HuaWeiFactory().createSystem();
// }
// }
public static void main(String[] args) {
System.out.println("请输入你想要的手机:苹果 or 华为");
Scanner scanner = new Scanner(System.in);
String str = scanner.nextLine();
Client client = new Client();
client.buyPhone(client.select(str));
client.use(client.selectSystem(str));
}
}
运行结果: