Java-马士兵设计模式学习笔记-工厂模式-简单工厂

一、概述

1.目标:要控制任意类型交通工具的生产模式

2.目标有两层意思(1)任意类型 (2)生产模式,所以对应的,要这两个层面上抽象(Movable,VehicleFactory),利用接口,实现多态

 

二、类结构

1.Interface Movable.java

2.Car.java

3.Plane.java

4.Interface VehicleFactory.java

5.CarFactory.java

6.PlaneFactory.java

Java-马士兵设计模式学习笔记-工厂模式-简单工厂

 

 

三、代码

1.Movable.java

public interface Movable {

	void run();

}

  

2.Car.java

public class Car implements Movable {



	public Car() {

	}



	public void run() {

		System.out.println("Car running...............");

	}

	

}

  

3.Plane.java

public class Plane implements Movable {



	@Override

	public void run() {

		System.out.println("飞机飞翔中。。。。");

	}



}

  

4.VehicleFactory.java

public interface VehicleFactory {

	Movable create();

}

  

5.CarFactory.java

public class CarFactory implements VehicleFactory {



	private static Car car = new Car();

	@Override

	public Movable create() {

		return car;

	}



}

  

6.PlaneFactory.java

public class PlaneFactory implements VehicleFactory {



	private static Plane plane = new Plane();

	@Override

	public Movable create() {

		return plane;

	}



}

  

7.Test.java

public class Test {

	

	@org.junit.Test

	public void test() {

		VehicleFactory factory = new CarFactory();

		Movable m1 = factory.create();

		m1.run();

		

		Movable m2 = factory.create();

		System.out.println(m1 == m2);

		System.out.println(m1.equals(m2));

		

		System.out.println("******************************");

		

		factory = new PlaneFactory();

		m1 = factory.create();

		m1.run();

		

		m2 = factory.create();

		System.out.println(m1 == m2);

		System.out.println(m1.equals(m2));

	}

}

  

8.测试结果

Java-马士兵设计模式学习笔记-工厂模式-简单工厂

你可能感兴趣的:(java)