定义:定义了一个创建对象的接口,但由子类决定要实例化的类是哪一个。工厂方法让类把实例化推迟到子类。
现在有一个工厂,提供了生产电脑的接口。
/**
* 工厂接口
* @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();
}
结果: