简单工厂模式

以下以例子来总结几种工厂模式,如有需要,请花点时间耐心阅读,谢谢。
2. 简单工厂设计模式:

情景:某人准备去买电脑,到电脑商城后发现两款电脑他很喜欢,一款是Macbook Pro,另一款是Surface Pro。

//创建接口电脑
interface Computer {
	void printComputer();
}
//创建具体工厂MacbookComputer实现接口电脑
class MacbookProComputer implements Computer {
	//覆写接口的抽象方法
	public void printComputer() {
		System.out.println("苹果电脑");
	}
}
//创建具体工厂SurfaceBookComputer实现接口电脑
class SurfaceBookComputer() implements Computer{
	//覆写接口的抽象方法
	public void printComputer() {
		System.out.println("微软电脑");
	}
}
public class Client {
	//创建买电脑的方法
	public void buyComputer(Computer computer) {
		computer.printComputer();
	}
	//选择电脑品牌
	public Computer select(String str) {
		if(str.equals("Mac") {
			return new MacbookProComputer();
		}else {
			return new SurfaceBookComputer();
		}
	}
	public static void main(String[] args) {
		System.out.println("请输入你想要的电脑品牌:Mac or Surface");
		Scanner scanner = new Scanner(System.in);
		String str = scanner.nextLine();
		Client client = new Client();
		client.buyComputer(client.select(str));
	}
}

工厂方法模式:

场景假设为:小明去买手机,手机品牌分为苹果手机和华为手机,而这两个手机都由各自的工厂生产,当需要购买哪种品牌的手机时,对应的工厂就生产手机,再输出给小明。

interface Phone {
	void printPhone();
}
class Iphone implements Phone {
	public void printPhone() {
		System.out.println("苹果手机");
	}
}
class HuaWei implements Phone {
	public void printPhone() {
		System.out.println("华为手机");
	}
}
interface PhoneFactory {
	Phone createPhone();
}
class IphoneFactory implements PhoneFactory {
	public Phone createPhone() {
		return new Iphone();
	}
}
class HuaWeiFactory implements PhoneFactory {
	public Phone createPhone() {
		return new HuaWei();
	}
}
public class Client  {
	public void buyPhone(Phone phone) {
		phone.printPhone();
	} 
	public Phone select(String str) {
		if(str.equals("苹果")) {
			return new IphoneFactory().createPhone();
		}else {
			return new HuaWeiFactory().createPhone();
		}
	}
	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));
	}
}

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值