简单工厂模式

简单工厂的定义:提供一个创建对象实例的功能,而无须关心其具体实现。被创建实例的类型可以是接口、抽象类,也可以是具体的类
实现汽车接口

  1. public interface Car {
  2. String getName();
  3. }

奔驰类

  1. public class Benz implements Car {
  2. @Override
  3. public String getName() {
  4. return "Benz";
  5. }
  6. }

宝马类

  1. public class BMW implements Car {
  2. @Override
  3. public String getName() {
  4. return "BMW";
  5. }
  6. }

简单工厂,既能生产宝马又能生产奔驰

  1. public class simpleFactory {
  2. public Car getCar(String name) {
  3. if ( name.equals("BMW")) {
  4. return new BMW();
  5. } else if ( name.equals("Benz")) {
  6. return new Benz();
  7. } else {
  8. System.out.println("no");
  9. return null;
  10. }
  11. }
  12. }

测试类

  1. public class SimpleFactoryTest {
  2. public static void main(String[] args) {
  3. simpleFactory simple = new simpleFactory();
  4. Car car = simple.getCar("BMW");
  5. System.out.println(car.getName());
  6. }
  7. }

工厂方法

工厂接口

  1. public interface Factory {
  2. Car getCar();
  3. }

奔驰工厂

  1. public class BenzFactory implements Factory {
  2. @Override
  3. public Car getCar() {
  4. return new Benz();
  5. }
  6. }

宝马工厂

  1. public class BMWFactory implements Factory {
  2. @Override
  3. public Car getCar() {
  4. return new BMW();
  5. }
  6. }

测试类

  1. public static void main(String[] args) {
  2. Factory bmwFactory = new BMWFactory();
  3. System.out.println(bmwFactory.getCar().getName());
  4. Factory benzFactory = new BenzFactory();
  5. System.out.println(benzFactory.getCar().getName());
  6. }

抽象工厂

抽象工厂

  1. public abstract class AbastractFactory {
  2. protected abstract Car getCar();
  3. public Car getCar(String name) {
  4. if ( "BMW".equalsIgnoreCase(name)) {
  5. return new BMWFactory().getCar();
  6. } else if ( "Benz".equalsIgnoreCase(name) ) {
  7. return new BenzFactory().getCar();
  8. } else {
  9. return null;
  10. }
  11. }
  12. }