如何使用Factory模式重构我的Java代码?

时间:2015-02-15 16:56:54

标签: java refactoring

我想使用Factory模式制作一个新方法addShip,它在运行时确定要初始化的Ship类型。

    while(!g.allShipsPlaced())
    {
        NumberGenerator gen = new NumberGenerator();
        int x = gen.rand(10);
        int y = gen.rand(10);
        int o = gen.rand(1);

        x = gen.rand(10);
        y = gen.rand(10);
        o = gen.rand(2);        
        System.out.println("vertical sub x = " + x + "\n");
        System.out.println("vertical sub y = " + y + "\n");
        g.addSub(x,y, o);

        x = gen.rand(10);
        y = gen.rand(10);
        o = gen.rand(2);        
        System.out.println("vertical battle x = " + x + "\n");
        System.out.println("vertical battle y = " + y + "\n");
        g.addBattle(x,y, o);    

        x = gen.rand(10);
        y = gen.rand(10);
        o = gen.rand(2);                
        System.out.println("vertical air x = " + x + "\n");
        System.out.println("vertical air y = " + y + "\n");
        g.addAir(x,y, o);

        x = gen.rand(10);
        y = gen.rand(10);
        o = gen.rand(2);                
        System.out.println("vertical mine x = " + x + "\n");
        System.out.println("vertical mine y = " + y + "\n");
        g.addMine(x,y, o);

        x = gen.rand(10);
        y = gen.rand(10);
        o = gen.rand(2);
        System.out.println("horizontal dest x = " + x + "\n");
        System.out.println("horizontal dest y = " + y + "\n");
        g.addDest(x,y, o);

    }

    System.out.println("agent grid");
    System.out.println(g.toString());

    return g;
}

例如,

    x = gen.rand(10); 
    y = gen.rand(10);
    o = gen.rand(2);        
    System.out.println("vertical sub x = " + x + "\n");
    System.out.println("vertical sub y = " + y + "\n");
    g.addShip(x, y, o, "Submarine");
    /* x,y are the coordinates to define where to place the ship and o
    defines how to place the ship (horizontal or vertical) */

从String类型中你可以看到应该初始化哪种类型的船,这意味着你要调用addSubmarine方法

以下是原始代码https://github.com/michaelokarimia/battleships/tree/master/Battleships的链接。您可以在Agent类中找到此代码。任何帮助表示赞赏。

1 个答案:

答案 0 :(得分:0)

如果要在代码中使用Factory模式,则应执行以下操作:

  1. 从抽象类Ship扩展所有Ship类。
  2. 创建一个抽象类AbstractShipFactory,其中包含方法Ship createShip(int, int, int)
  3. 创建具体的类,如BattleShipFactoryDestShipFactory等,这些类扩展AbstractShipFactory并覆盖createShip
  4. 在代码中使用工厂:

    while(!g.allShipsPlaced())
    {
        NumberGenerator gen = new NumberGenerator();
        AbstractShipFactory battleFactory = new BattleShipFactory();
        ...
        g.addShip(battleFactory.createShip(gen.rand(), gen.rand(), gen.rand()));
        ...
    }
    
  5. 它叫做工厂方法。请注意,您必须为每种新产品类型创建新工厂。