zoukankan      html  css  js  c++  java
  • 设计模式-3-简单工厂

    简介:工厂类根据传入参数,创建对应的实现类

    目的:根据传入参数,提供对应的实现类

    总结:工厂类根据传入参数,创建对应的实现类

    主要组成:  接口, 实现类, 工厂类

    接口:

    GameService.java

    package com.design.c.factory.simple;
    
    public interface GameService {
    
        /**
         * 游戏方法
         */
        void play();
    }

    实现类:

    AGameServiceImpl.java

    package com.design.c.factory.simple;
    
    public class AGameServiceImpl implements GameService {
    
        @Override
        public void play() {
            System.out.println("Playing AngryBird Game  ... ... ");
        }
    
    }

    BGameServiceImpl.java

    package com.design.c.factory.simple;
    
    public class BGameServiceImpl implements GameService {
    
        @Override
        public void play() {
            System.out.println("Playing LOL Game  ... ... ");
        }
    
    }

    工厂类:

    package com.design.c.factory.simple;
    /**
     * 简单工厂模式
     * 
     * 简介:由一个工厂对象决定创建出哪一种实例
     */
    public class SimpleFactory {
        
        //1-私有化构造方法
        private SimpleFactory(){};
    
        //2-根据传递给工厂类的参数,决定创建那种实例
        public static GameService createGameService(String gameName){
            
            if(gameName == null){
                return null;
            }
            
            if("A".equals(gameName)){
                return new AGameServiceImpl();
            }else if("B".equals(gameName)){
                return new BGameServiceImpl();
            }
            
            return null;
        }
    }

    Main:

    package com.design.c.factory.simple;
    
    public class MainTest {
    
        public static void main(String[] args) {
            
            /**
             * 3-简单工厂模式
             */
            GameService lolGame = SimpleFactory.createGameService("A");
            lolGame.play();
            GameService angryBirdGame = SimpleFactory.createGameService("B");
            angryBirdGame.play();
        }
    }

    Result:

    Playing AngryBird Game  ... ... 
    Playing LOL Game  ... ... 
  • 相关阅读:
    checkedListBox的具体用法
    pi
    从1.9G到64K
    世界编程大赛第一名程序
    SQLServer中导入/导出Excel的基本方法
    Android 内存优化测试
    android,内存优化详解
    Android解决大图片内存溢出
    Android有效解决加载大图片时内存溢出的问题
    android端读取本地图片出现OutOfMemoryException
  • 原文地址:https://www.cnblogs.com/wanhua-wu/p/7196643.html
Copyright © 2011-2022 走看看