zoukankan      html  css  js  c++  java
  • 利用接口实现简单工厂模式

     1 package com.wisezone.factory;
     2 
     3 /**
     4  * 使用接口实现一个水果工厂
     5  * @author 王东海
     6  * @2017年4月16日
     7  */
     8 public interface Fruit
     9 {
    10     void eat();
    11 }
     1 package com.wisezone.factory;
     2 
     3 /**
     4  * 苹果
     5  * @author 王东海
     6  * @2017年4月16日
     7  */
     8 public class Apple implements Fruit
     9 {
    10 
    11     @Override
    12     public void eat()
    13     {
    14         System.out.println("夏天吃苹果。。。");
    15     }
    16 
    17 }
     1 package com.wisezone.factory;
     2 
     3 /**
     4  * 梨
     5  * @author 王东海
     6  * @2017年4月16日
     7  */
     8 public class Pear implements Fruit
     9 {
    10 
    11     @Override
    12     public void eat()
    13     {
    14         System.out.println("夏天吃梨。。。");
    15         
    16     }
    17 
    18 }
     1 package com.wisezone.factory;
     2 
     3 /**
     4  * 简单工厂模式----利用接口----实现水果工厂
     5  * @author 王东海
     6  * @2017年4月16日
     7  */
     8 public class FactoryInterface
     9 {
    10     public static Fruit product(String type){
    11         if ("apple".equalsIgnoreCase(type))
    12         {
    13             return new Apple();
    14         }else if ("pear".equalsIgnoreCase(type))
    15         {
    16             return new Pear();
    17         }
    18         return null;
    19     }
    20     
    21     public static void main(String[] args)
    22     {
    23         Fruit fruit = FactoryInterface.product("apple");
    24         fruit.eat();
    25     }
    26 }

    结果为:夏天吃苹果。。。

  • 相关阅读:
    3、Spring Cloud Rest工程创建(通过IDEA创建)
    Centos7配置阿里epel源|yum源
    OSI七层模型:TCP/IP && HTTP && WebSocket && MQTT
    几种进程间的通信方式
    Tomcat类加载机制
    JAVA类加载器
    Spring事务隔离级别
    Spring事务传播特性
    Spring事务实现原理
    RPC框架Dubbo分析
  • 原文地址:https://www.cnblogs.com/wdh1995/p/6719181.html
Copyright © 2011-2022 走看看