抽象工厂模式

以下以例子来总结几种工厂模式,如有需要,请花点时间耐心阅读,谢谢。
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));
	}
}

运行结果:
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值