JAVA设计模式——工厂模式

 概述

工厂设计模式提供一个工厂,在用到其他实体时候不通过new 的方式,而通过提供的工厂类中的方法返回其需要的实体。

简单工厂

定义一个产品,创建一个接口

1 /**
2  * 飞机
3  * @author Shinelon
4  *
5  */
6 public interface Plane {
7     public String getModelType();
8 }

同一类产品有不同型号规格

 1 /**
 2  * A型飞机
 3  * @author Shinelon
 4  *
 5  */
 6 public class PlaneA implements Plane{
 7 
 8     @Override
 9     public String getModelType() {
10         return "A";
11     }
12     
13 }
 1 /**
 2  * B型飞机
 3  * @author Shinelon
 4  *
 5  */
 6 public class PlaneB implements Plane{
 7 
 8     @Override
 9     public String getModelType() {
10         return "B";
11     }
12 
13 }

一个生产产品的工厂

 1 /**
 2  * 飞机工厂
 3  * @author Shinelon
 4  *
 5  */
 6 public class PlaneFactory {
 7     /**
 8      * @param modelName 型号
 9      * @return
10      */
11     public Plane getPlane(String modelType) {
12         if ("A".equals(modelType)) {
13             return new PlaneA();
14         }else if ("B".equals(modelType)) {
15             return new PlaneB();
16         }else {
17             System.out.println("生产不出此种型号。");
18             return null;
19         }
20     }
21 }

简单的调用代码

 1 public class TestDemo {
 2     public static void main(String[] args) {
 3         PlaneFactory planeFactory = new PlaneFactory();
 4         // 根据客户要求生产不同型号飞机
 5         Plane plane1 = planeFactory.getPlane("A");
 6         Plane plane2 = planeFactory.getPlane("B");
 7         System.out.println(plane1.getModelType());
 8         System.out.println(plane2.getModelType());
 9     }
10 }

 待续!!

posted on 2018-03-04 15:30  SaltFishYe  阅读(115)  评论(0)    收藏  举报

导航