zoukankan      html  css  js  c++  java
  • 创建型模式之 -- 工厂方法模式

    1.普通工厂模式

        目录结构大致为这样:

     

    1.创建一个游戏接口:

    public interface PlayGame {
        public void game(); 
    }

        2.游戏分别被两种设备实现

    public class Computer implements PlayGame{
    
        @Override
        public void game() {
            System.err.println("玩电脑游戏!!");
        }
    }
    public class Phone implements PlayGame {
    
        @Override
        public void game() {
            System.err.println("玩手机游戏");
        }
    
    }

        3.创建游戏工厂

    /**
     * 玩游戏工厂
     * @author 淹死的鱼o0
     */
    public class PlayGameFactory {
    
        public PlayGame produce(String type){
            if ("phone".equals(type)) {  
                return new Phone();  
            } else if ("computer".equals(type)) {  
                return new Computer();  
            } else {  
                System.err.println("请输入游戏设备!");  
                return null;  
            }  
        }
    }

        4.测试:

    public class PlayGameTest {
        @Test
        public void gameTest() {
            PlayGameFactory factory = new PlayGameFactory();
            //PlayGame game = factory.produce("computer");
            //game.game();
            PlayGame game = factory.produce("phone");
            game.game();
        }
    }

        5.输出

    2.多个工厂方法模式,是对普通工厂方法模式的改进

        将上面代码做如下修改

    /**
     * 玩游戏工厂
     * 
     * @author 淹死的鱼o0
     */
    public class PlayGameFactory {
        public PlayGame producePhone() {
            return new Phone();
        }
    
        public PlayGame produceComputer() {
            return new Computer();
        }
    }

        测试:

    public class PlayGameTest {
        @Test
        public void gameTest() {
            PlayGameFactory factory = new PlayGameFactory();
            PlayGame game = factory.producePhone();
            game.game();
        }
    }

    3.静态工厂方法模式

        

    /**
     * 玩游戏工厂
     * 
     * @author 淹死的鱼o0
     */
    public class PlayGameFactory {
        public static PlayGame producePhone() {
            return new Phone();
        }
    
        public static PlayGame produceComputer() {
            return new Computer();
        }
    }

    总结:工厂模式适合用来快速创建对象.

    欢迎转载:

    中文名:惠凡

    博客名:淹死的鱼o0

    转载时请说明出处:http://www.cnblogs.com/huifan/

  • 相关阅读:
    Codeforces Round #544 (Div. 3) C. Balanced Team
    Codeforces Round #544 (Div. 3) B.Preparation for International Women's Day
    Codeforces Round #544 (Div. 3) A.Middle of the Contest
    HDU-2647-Reward
    2015.3.15
    USACO Section 5.1 Musical Themes(枚举)
    [STOI2014]舞伴(dp)
    USACO Section 5.1 Fencing the Cows(凸包)
    2015.3.10
    USACO Section 4.3 Street Race(图的连通性+枚举)
  • 原文地址:https://www.cnblogs.com/huifan/p/8336813.html
Copyright © 2011-2022 走看看