zoukankan      html  css  js  c++  java
  • 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

    三、代码

    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.测试结果

  • 相关阅读:
    加分二叉树
    香甜的黄油 Sweet Butter
    09.22今日暂时停更题解
    能量项链
    转圈游戏
    字串变换
    关押罪犯
    选择客栈
    神经网络
    未整理算法的总结
  • 原文地址:https://www.cnblogs.com/shamgod/p/4586349.html
Copyright © 2011-2022 走看看