设计模式之工厂方法
工厂方法是在简单工厂的基础上的进一步抽象,在简单工厂中,所有的对象都是通过一个工厂来创建,在工厂方法中,每个对象都有特定的工厂来创建。
抽象接口(车)
package com.yf.designpattern.factorymethod;public interface Car {public void drive();}
package com.yf.designpattern.factorymethod;public class BmwCar implements Car {@Overridepublic void drive() {System.out.println("This is a BMW!!!");}}package com.yf.designpattern.factorymethod;public class BenzCar implements Car {@Overridepublic void drive() {System.out.println("This is a Benz!!!");}}
package com.yf.designpattern.factorymethod;public interface CarFactory {public Car driver();}
package com.yf.designpattern.factorymethod;//奔驰车厂只生产奔驰车public class BenzCarFactory implements CarFactory {@Overridepublic Car driver() {// TODO Auto-generated method stubreturn new BenzCar();}}package com.yf.designpattern.factorymethod;//宝马车厂只生产宝马车public class BmwCarFactory implements CarFactory {@Overridepublic Car driver() {// TODO Auto-generated method stubreturn new BmwCar();}}
package com.yf.designpattern.factorymethod;public class Test {/** * @param args */public static void main(String[] args) {CarFactory cf=new BmwCarFactory();Car car=cf.driver();car.drive();}}