Factory Method

Factory Method
定义一个创建对象的接口,由子类决定实例化哪一个类,工厂方法将类的实例化推迟到子类实现。
多个子类都实现各自的重写的接口的方法。
当需要使用接口方法时候,通过创建不同的子类从而实现创建不同的对象。


//定义游戏接口
interface Game {
    public void play();
}

//A游戏
class GameA implements Game{
    public void play(){System.out.println("Playing GameA");};
}

//B游戏
class GameB implements Game{
    public void play(){System.out.println("Playing GameB");};
}

//C游戏
class GameC implements Game{
    public void play(){System.out.println("Playing GameC");};
}

//定义工厂(父类)
interface GameFactory {
    Game createGame();
}

//帮忙子类,游戏A工厂
class GameAFactory implements GameFactory {
    @Override
    public Game createGame() {
        return new GameA();
    }
}

//帮忙子类,游戏B工厂
class GameBFactory implements GameFactory {
    @Override
    public Game createGame() {
        return new GameB();
    }
}

//帮忙子类,游戏C工厂
class GameCFactory implements GameFactory {
    @Override
    public Game createGame() {
        return new GameC();
    }
}

//测试者(客户)类
class Tester {
    private GameFactory gameFactory;

    public Tester(GameFactory gameFactory) {
        this.gameFactory = gameFactory;
    }

    public void testGame() {
        //通过工厂获取游戏实例
        Game game = gameFactory.createGame();
        //试玩游戏
        game.play();
    }

}

//代码测试
public class Test {
    public static void main(String[] args) {
        //要求测试者1试玩游戏A
        GameFactory gameFactory = new GameAFactory();
        Tester tester1 = new Tester(gameFactory);
        tester1.testGame();
        
         //要求测试者2也试玩游戏A
        Tester tester2 = new Tester(gameFactory);
        tester2.testGame();
        
        //... 测试者1000也试玩游戏A
    }
}

你可能感兴趣的:(设计模式,工厂方法模式,java,开发语言)