码迷,mamicode.com
首页 > 其他好文 > 详细

设计模式-3-简单工厂

时间:2017-07-17 18:41:00      阅读:149      评论:0      收藏:0      [点我收藏+]

标签:tor   rgs   stat   接口   null   factory   nbsp   ice   package   

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

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

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

 

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

接口:

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  ... ... 

 

设计模式-3-简单工厂

标签:tor   rgs   stat   接口   null   factory   nbsp   ice   package   

原文地址:http://www.cnblogs.com/wanhua-wu/p/7196643.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!