@Override public void feel() { System.out.println("高端座椅,坐着舒适"); } }
class LowEndSeat implements Seat {
@Override public void feel() { System.out.println("低端座椅,坐旧难受"); } }
工厂模式的前提:创建的实例通常都具有共同的父类,此处使用接口作为“父类”。
如果使用工厂方法模式,代码如下:
1 2 3 4 5 6 7 8 9 10 11 12
public interface EngineFactory { Engine createEngine(); }
public interface TyreFactory { Tyre createTyre(); }
public interface SeatFactory{ Seat createSeat(); } ...
发动机、轮胎、座椅 3 个产品需要创建 3 个抽象工厂与 6 个实现类(高端和低端)。
客户端调用:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
public class Client {
public static void main(String[] args) { EngineFactory ef = new HighEndEngineFactory(); Engine engine = ef.createEngine();
TyreFactory tf = new HighEndTyreFactory(); Tyre tyre = tf.createTyre(); SeatFactory sf = new HighEndEngineSeatFactory(); Seat seat = sf.createSeat(); } }