创建型模式之 -- 工厂方法模式

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/

原文地址:https://www.cnblogs.com/huifan/p/8336813.html