工厂方法(Factory Method)

Posted huan30

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了工厂方法(Factory Method)相关的知识,希望对你有一定的参考价值。

  工厂方法-(Factory Method) : 定义一个用于创建产品的接口,由子类决定生产什么产品

/**
 * 定义一个交通工具
 */
public interface Vehicle {
    void go();
}
/**
 * 飞行扫把
 */
public class Broom implements Vehicle {
    @Override
    public void go() {
        System.out.println("broom go");
    }
}
/**
 * 汽车
 */
public class Car implements Vehicle {
    @Override
    public void go() {
        System.out.println("car go");
    }
}
/**
 * 飞机
 */
public class Plane implements Vehicle {
    @Override
    public void go() {
        System.out.println("plane go ");
    }
}

  

/**
 * 交通创建工厂
 */
public interface VehicleFactory {
    Vehicle create();
}
public class BroomFactory implements VehicleFactory {
    @Override
    public Vehicle create() {
        System.out.println(" create broom before");
        return new Broom();
    }
}
public class CarFactory implements VehicleFactory {
    @Override
    public Vehicle create() {
        System.out.println(" create car before");
        return new Car();
    }
}
public class PlaneFactory implements VehicleFactory {
    @Override
    public Vehicle create() {
        System.out.println(" create plane before");
        return new Plane();
    }
}

  

以上是关于工厂方法(Factory Method)的主要内容,如果未能解决你的问题,请参考以下文章

工厂方法 Factory Method

工厂方法 Factory Method

工厂方法模式(Factory Method)

设计模式工厂方法模式(Factory Method)

java设计模式:工厂方法模式(Factory Method)

C#设计模式详解——Factory Method(工厂方法)