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

How can I use the Factory pattern to refactor my Java code?

我想使用工厂模式创建一个新方法 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的一个link。您可以在代理 class 中找到此代码。感谢任何帮助。

如果您想在代码中使用工厂模式,您应该执行以下操作:

  1. 从摘要 class Ship.
  2. 中扩展所有 Ship classes
  3. 创建一个抽象 class AbstractShipFactory,它有一个方法 Ship createShip(int, int, int)
  4. 创建具体的 class,例如 BattleShipFactoryDestShipFactory 等,它们扩展 AbstractShipFactory 并覆盖 createShip
  5. 在您的代码中使用工厂:

    while(!g.allShipsPlaced())
    {
        NumberGenerator gen = new NumberGenerator();
        AbstractShipFactory battleFactory = new BattleShipFactory();
        ...
        g.addShip(battleFactory.createShip(gen.rand(), gen.rand(), gen.rand()));
        ...
    }
    

它叫做工厂方法。请注意,您必须为每种新产品类型创建新工厂。