工厂方法模式

定义:定义了一个创建对象的接口,但由子类决定要实例化的类是哪一个。工厂方法让类把实例化推迟到子类。

现在有一个工厂,提供了生产电脑的接口。

/**
 * 工厂接口
 * @author z_hh
 * @time 2018年10月27日
 */
public interface Factory {

	/**
	 * 生产电脑
	 * @return 电脑接口
	 */
	Computer create();
	
}

它有两个实现类,分别生产联想电脑和戴尔电脑。

/**
 * 联想工厂
 * @author z_hh
 * @time 2018年10月27日
 */
public class LenovoFactory implements Factory {

	@Override
	public Computer create() {
		return new LenovoComputer();
	}

}
/**
 * 戴尔工厂
 * @author z_hh
 * @time 2018年10月27日
 */
public class DellFactory implements Factory {

	@Override
	public Computer create() {
		return new DellComputer();
	}

}

联想电脑和戴尔电脑都继承了电脑类,覆盖了开机方法。

/**
 * 电脑抽象类
 * @author z_hh
 * @time 2018年10月27日
 */
public abstract class Computer {
	
	/**
	 * 开机
	 */
	abstract void turnOn();
}
/**
 * 联想电脑
 * @author z_hh
 * @time 2018年10月27日
 */
public class LenovoComputer extends Computer {

	@Override
	public void turnOn() {
		System.out.println("欢迎使用联想电脑!");
	}

}
/**
 * 戴尔电脑
 * @author z_hh
 * @time 2018年10月27日
 */
public class DellComputer extends Computer {

	@Override
	public void turnOn() {
		System.out.println("欢迎使用戴尔电脑!");
	}
	
}

使用的时候,通过调用不同的工厂实现类,来创建不同的类实例。

public static void main(String[] args) {
		// 联想商店生产电脑
		Factory computerStore = new LenovoFactory();
		Computer computer = computerStore.create();
		computer.turnOn();
		
		// 戴尔商店生产电脑
		computerStore = new DellFactory();
		computer = computerStore.create();
		computer.turnOn();
}

结果:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值