草庐IT

java - 实现工厂设计模式时如何避免 'instanceof'?

coder 2023-05-15 原文

我正在尝试实现我的第一个工厂设计模式,但我不确定在将工厂制造的对象添加到列表时如何避免使用 instanceof。这就是我想要做的:

for (Blueprint bp : blueprints) {
    Vehicle v = VehicleFactory.buildVehicle(bp);
    allVehicles.add(v);
                
    // Can I accomplish this without using 'instanceof'?
    if (v instanceof Car) {
        cars.add((Car) v);
    } else if (v instanceof Boat) {
        boats.add((Boat) v);
    } else if (v instanceof Plane) {
        planes.add((Plane) v);
    }
}

根据我在 Stack Overflow 上阅读的内容,使用“instanceof”是一种代码异味。有没有更好的方法来检查工厂创建的车辆类型而不使用'instanceof'?

我欢迎对我的实现提出任何反馈/建议,因为我什至不确定我是否以正确的方式进行。

下面的完整示例:

import java.util.ArrayList;

class VehicleManager {
    
    public static void main(String[] args) {
        
        ArrayList<Blueprint> blueprints = new ArrayList<Blueprint>();
        ArrayList<Vehicle> allVehicles = new ArrayList<Vehicle>();
        ArrayList<Car> cars = new ArrayList<Car>();
        ArrayList<Boat> boats = new ArrayList<Boat>();
        ArrayList<Plane> planes = new ArrayList<Plane>();
        
        /*
        *  In my application I have to access the blueprints through an API
        *  b/c they have already been created and stored in a data file.
        *  I'm creating them here just for example.
        */
        Blueprint bp0 = new Blueprint(0);
        Blueprint bp1 = new Blueprint(1);
        Blueprint bp2 = new Blueprint(2);
        blueprints.add(bp0);
        blueprints.add(bp1);
        blueprints.add(bp2);
        
        for (Blueprint bp : blueprints) {
            Vehicle v = VehicleFactory.buildVehicle(bp);
            allVehicles.add(v);
            
            // Can I accomplish this without using 'instanceof'?
            if (v instanceof Car) {
                cars.add((Car) v);
            } else if (v instanceof Boat) {
                boats.add((Boat) v);
            } else if (v instanceof Plane) {
                planes.add((Plane) v);
            }
        }
        
        System.out.println("All Vehicles:");
        for (Vehicle v : allVehicles) {
            System.out.println("Vehicle: " + v + ", maxSpeed: " + v.maxSpeed);
        }
        
        System.out.println("Cars:");
        for (Car c : cars) {
            System.out.println("Car: " + c + ", numCylinders: " + c.numCylinders);
        }
        
        System.out.println("Boats:");
        for (Boat b : boats) {
            System.out.println("Boat: " + b + ", numRudders: " + b.numRudders);
        }
        
        System.out.println("Planes:");
        for (Plane p : planes) {
            System.out.println("Plane: " + p + ", numPropellers: " + p.numPropellers);
        }
    }
}

class Vehicle {
    
    double maxSpeed;
    
    Vehicle(double maxSpeed) {
        this.maxSpeed = maxSpeed;
    }
}

class Car extends Vehicle {
    
    int numCylinders;
    
    Car(double maxSpeed, int numCylinders) {
        super(maxSpeed);
        this.numCylinders = numCylinders;
    }
}

class Boat extends Vehicle {
    
    int numRudders;
    
    Boat(double maxSpeed, int numRudders) {
        super(maxSpeed);
        this.numRudders = numRudders;
    }
}

class Plane extends Vehicle {
    
    int numPropellers;
    
    Plane(double maxSpeed, int numPropellers) {
        super(maxSpeed);
        this.numPropellers = numPropellers;
    }
}

class VehicleFactory {
    
    public static Vehicle buildVehicle(Blueprint blueprint) {
        
        switch (blueprint.type) {
            
            case 0:
                return new Car(100.0, 4);
                
            case 1:
                return new Boat(65.0, 1);
                
            case 2:
                return new Plane(600.0, 2);
                
            default:
                return new Vehicle(0.0);
        }
    }
}

class Blueprint {
    
    int type; // 0 = car; // 1 = boat; // 2 = plane;
    
    Blueprint(int type) {
        this.type = type;
    }
}

最佳答案

您可以实现 Visitor pattern .


详细解答

这个想法是使用polymorphism执行类型检查。每个子类都覆盖 accept(Visitor) 方法,该方法应在父类(super class)中声明。当我们遇到如下情况时:

void add(Vehicle vehicle) {
    //what type is vehicle??
}

我们可以将对象传递给 Vehicle 中声明的方法。如果 vehicleCar 类型,并且 class Car 覆盖了我们将对象传递到其中的方法,则该对象现在将在声明的方法中处理在 Car 类中。我们利用这个优势:创建一个 Visitor 对象并将其传递给一个覆盖的方法:

abstract class Vehicle {
    public abstract void accept(AddToListVisitor visitor);
}

class Car extends Vehicle {
    public void accept(AddToListVisitor visitor) {
        //gets handled in this class
    }
}

这个Visitor应该准备访问类型Car。您想要避免使用 instanceof 来查找实际类型的任何类型都必须在 Visitor 中指定。

class AddToListVisitor {
    public void visit(Car car) {
        //now we know the type! do something...
    }

    public void visit(Plane plane) {
        //now we know the type! do something...
    }
}

这里是进行类型检查的地方!

Car 接收到访问者时,它应该使用this 关键字传入。由于我们在类 Car 中,因此将调用方法 visit(Car)。在我们的访问者内部,我们可以执行我们想要的操作,因为我们知道对象的类型。


所以,从顶部开始:

您创建一个 Visitor,它执行您想要的操作。访问者应包含您要对其执行操作的每种类型的对象的 visit 方法。在这种情况下,我们正在为车辆创建访问者:

interface VehicleVisitor {
    void visit(Car car);
    void visit(Plane plane);
    void visit(Boat boat);
}

我们想要执行的操作是将车辆添加到某物上。我们将创建一个 AddTransportVisitor;管理添加交通工具的访客:

class AddTransportVisitor implements VehicleVisitor {
    public void visit(Car car) {
        //add to car list
    }

    public void visit(Plane plane) {
        //add to plane list
    }

    public void visit(Boat boat) {
        //add to boat list
    }
}

每辆车都应该能够接受车辆访客:

abstract class Vehicle {
    public abstract void accept(VehicleVisitor visitor);
}

当访问者被传递给车辆时,车辆应该调用它的 visit 方法,将自身传递到参数中:

class Car extends Vehicle {
    public void accept(VehicleVisitor visitor) {
        visitor.visit(this);
    }
}

class Boat extends Vehicle {
    public void accept(VehicleVisitor visitor) {
        visitor.visit(this);
    }
}

class Plane extends Vehicle {
    public void accept(VehicleVisitor visitor) {
        visitor.visit(this);
    }
}

这就是类型检查发生的地方。调用了正确的 visit 方法,其中包含要根据方法的参数执行的正确代码。

最后一个问题是让 VehicleVisitor 与列表交互。这就是您的 VehicleManager 的用武之地:它封装了列表,允许您通过 VehicleManager#add(Vehicle) 方法添加车辆。

当我们创建访问者时,我们可以将管理器传递给它(可能通过它的构造函数),所以我们可以执行我们想要的操作,因为我们知道对象的类型。 VehicleManager 应该包含访问者并拦截 VehicleManager#add(Vehicle) 调用:

class VehicleManager {
    private List<Car> carList = new ArrayList<>();
    private List<Boat> boatList = new ArrayList<>();
    private List<Plane> planeList = new ArrayList<>();

    private AddTransportVisitor addVisitor = new AddTransportVisitor(this);

    public void add(Vehicle vehicle) {
        vehicle.accept(addVisitor);
    }

    public List<Car> getCarList() {
        return carList;
    }

    public List<Boat> getBoatList() {
        return boatList;
    }

    public List<Plane> getPlaneList() {
        return planeList;
    }
}

我们现在可以为 AddTransportVisitor#visit 方法编写实现:

class AddTransportVisitor implements VehicleVisitor {
    private VehicleManager manager;

    public AddTransportVisitor(VehicleManager manager) {
        this.manager = manager;
    }

    public void visit(Car car) {
        manager.getCarList().add(car);
    }

    public void visit(Plane plane) {
        manager.getPlaneList().add(plane);
    }

    public void visit(Boat boat) {
       manager.getBoatList().add(boat);
    }
}

我强烈建议删除 getter 方法并为每种类型的车辆声明重载的 add 方法。这将减少不需要时“访问”的开销,例如 manager.add(new Car()):

class VehicleManager {
    private List<Car> carList = new ArrayList<>();
    private List<Boat> boatList = new ArrayList<>();
    private List<Plane> planeList = new ArrayList<>();

    private AddTransportVisitor addVisitor = new AddTransportVisitor(this);

    public void add(Vehicle vehicle) {
        vehicle.accept(addVisitor);
    }

    public void add(Car car) {
        carList.add(car);
    }

    public void add(Boat boat) {
        boatList.add(boat);
    }

    public void add(Plane plane) {
        planeList.add(plane);
    }

    public void printAllVehicles() {
        //loop through vehicles, print
    }
}

class AddTransportVisitor implements VehicleVisitor {
    private VehicleManager manager;

    public AddTransportVisitor(VehicleManager manager) {
        this.manager = manager;
    }

    public void visit(Car car) {
        manager.add(car);
    }

    public void visit(Plane plane) {
        manager.add(plane);
    }

    public void visit(Boat boat) {
       manager.add(boat);
    }
}

public class Main {
    public static void main(String[] args) {
        Vehicle[] vehicles = {
            new Plane(),
            new Car(),
            new Car(),
            new Car(),
            new Boat(),
            new Boat()
        };

        VehicleManager manager = new VehicleManager();
            for(Vehicle vehicle : vehicles) {
                manager.add(vehicle);
            }

            manager.printAllVehicles();
    }
}

关于java - 实现工厂设计模式时如何避免 'instanceof'?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29458676/

有关java - 实现工厂设计模式时如何避免 'instanceof'?的更多相关文章

  1. ruby - 如何使用 Nokogiri 的 xpath 和 at_xpath 方法 - 2

    我正在学习如何使用Nokogiri,根据这段代码我遇到了一些问题:require'rubygems'require'mechanize'post_agent=WWW::Mechanize.newpost_page=post_agent.get('http://www.vbulletin.org/forum/showthread.php?t=230708')puts"\nabsolutepathwithtbodygivesnil"putspost_page.parser.xpath('/html/body/div/div/div/div/div/table/tbody/tr/td/div

  2. ruby - 如何从 ruby​​ 中的字符串运行任意对象方法? - 2

    总的来说,我对ruby​​还比较陌生,我正在为我正在创建的对象编写一些rspec测试用例。许多测试用例都非常基础,我只是想确保正确填充和返回值。我想知道是否有办法使用循环结构来执行此操作。不必为我要测试的每个方法都设置一个assertEquals。例如:describeitem,"TestingtheItem"doit"willhaveanullvaluetostart"doitem=Item.new#HereIcoulddotheitem.name.shouldbe_nil#thenIcoulddoitem.category.shouldbe_nilendend但我想要一些方法来使用

  3. python - 如何使用 Ruby 或 Python 创建一系列高音调和低音调的蜂鸣声? - 2

    关闭。这个问题是opinion-based.它目前不接受答案。想要改进这个问题?更新问题,以便editingthispost可以用事实和引用来回答它.关闭4年前。Improvethisquestion我想在固定时间创建一系列低音和高音调的哔哔声。例如:在150毫秒时发出高音调的蜂鸣声在151毫秒时发出低音调的蜂鸣声200毫秒时发出低音调的蜂鸣声250毫秒的高音调蜂鸣声有没有办法在Ruby或Python中做到这一点?我真的不在乎输出编码是什么(.wav、.mp3、.ogg等等),但我确实想创建一个输出文件。

  4. ruby-on-rails - rails : "missing partial" when calling 'render' in RSpec test - 2

    我正在尝试测试是否存在表单。我是Rails新手。我的new.html.erb_spec.rb文件的内容是:require'spec_helper'describe"messages/new.html.erb"doit"shouldrendertheform"dorender'/messages/new.html.erb'reponse.shouldhave_form_putting_to(@message)with_submit_buttonendendView本身,new.html.erb,有代码:当我运行rspec时,它失败了:1)messages/new.html.erbshou

  5. ruby-on-rails - 如何验证 update_all 是否实际在 Rails 中更新 - 2

    给定这段代码defcreate@upgrades=User.update_all(["role=?","upgraded"],:id=>params[:upgrade])redirect_toadmin_upgrades_path,:notice=>"Successfullyupgradeduser."end我如何在该操作中实际验证它们是否已保存或未重定向到适当的页面和消息? 最佳答案 在Rails3中,update_all不返回任何有意义的信息,除了已更新的记录数(这可能取决于您的DBMS是否返回该信息)。http://ar.ru

  6. ruby-on-rails - Rails - 子类化模型的设计模式是什么? - 2

    我有一个模型:classItem项目有一个属性“商店”基于存储的值,我希望Item对象对特定方法具有不同的行为。Rails中是否有针对此的通用设计模式?如果方法中没有大的if-else语句,这是如何干净利落地完成的? 最佳答案 通常通过Single-TableInheritance. 关于ruby-on-rails-Rails-子类化模型的设计模式是什么?,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.co

  7. ruby-on-rails - 'compass watch' 是如何工作的/它是如何与 rails 一起使用的 - 2

    我在我的项目目录中完成了compasscreate.和compassinitrails。几个问题:我已将我的.sass文件放在public/stylesheets中。这是放置它们的正确位置吗?当我运行compasswatch时,它不会自动编译这些.sass文件。我必须手动指定文件:compasswatchpublic/stylesheets/myfile.sass等。如何让它自动运行?文件ie.css、print.css和screen.css已放在stylesheets/compiled。如何在编译后不让它们重新出现的情况下删除它们?我自己编译的.sass文件编译成compiled/t

  8. ruby-on-rails - Railstutorial : db:populate vs. 工厂女孩 - 2

    在railstutorial中,作者为什么选择使用这个(代码list10.25):http://ruby.railstutorial.org/chapters/updating-showing-and-deleting-usersnamespace:dbdodesc"Filldatabasewithsampledata"task:populate=>:environmentdoRake::Task['db:reset'].invokeUser.create!(:name=>"ExampleUser",:email=>"example@railstutorial.org",:passwo

  9. ruby - 如何将脚本文件的末尾读取为数据文件(Perl 或任何其他语言) - 2

    我正在寻找执行以下操作的正确语法(在Perl、Shell或Ruby中):#variabletoaccessthedatalinesappendedasafileEND_OF_SCRIPT_MARKERrawdatastartshereanditcontinues. 最佳答案 Perl用__DATA__做这个:#!/usr/bin/perlusestrict;usewarnings;while(){print;}__DATA__Texttoprintgoeshere 关于ruby-如何将脚

  10. ruby - 如何指定 Rack 处理程序 - 2

    Rackup通过Rack的默认处理程序成功运行任何Rack应用程序。例如:classRackAppdefcall(environment)['200',{'Content-Type'=>'text/html'},["Helloworld"]]endendrunRackApp.new但是当最后一行更改为使用Rack的内置CGI处理程序时,rackup给出“NoMethodErrorat/undefinedmethod`call'fornil:NilClass”:Rack::Handler::CGI.runRackApp.newRack的其他内置处理程序也提出了同样的反对意见。例如Rack

随机推荐