我正在寻找一种解决方案,允许单个 Cars 类包含
每个汽车对象。我不想要不同的收藏(比如克尔维特,
旧车)。我也在寻找一种允许创建的解决方案
基于单个汽车类型属性的汽车对象...如
前面提到过,创造一款类似 Corvette 的新车将导致
以0.9的速度。不应该有其他方法来指定汽车
速度。
天哪,天哪,有很多方法可以解决这个问题,我们可以继续一整天!我会做一次大脑转储,希望这对你来说不会太难处理。
解决方案1:使用策略。
策略基本上是一种将大量可替换逻辑与另一个类分开的方法。在这种情况下,每辆车都需要进行不同的设计。对此,有一个策略是完美的。
抱歉,如果我不小心混入了一些 C#...自从我使用 java 以来已经很长时间了。
public interface CarCreationStrategy{
void BuildCar(Car theCar);
}
public class CorvetteStrategy implements CarCreationStrategy{
public void BuildCar(Car theCar){
theCar.Type = "Corvette";
theCar.Speed = 0.9;
theCar.Comments = "Speedster!";
}
}
public class ToyotaStrategy implements CarCreationStrategy{
public void BuildCar(Car theCar){
theCar.Type = "Toyota";
theCar.Speed = "0.5";
theCar.Comments = "Never dies, even if you drop it from the top of a building";
}
}
现在,您可以向汽车构造函数传递策略。
public class Car{
// Variables ...
public Car(CarCreationStrategy strategy, int year){
strategy.BuildCar(this); // Implements your properties here.
this.year = year;
}
}
所以,你现在得到的东西真是太棒了!
List<Car> cars = new List<Car>();
cars.Add(new Car(new CorvetteStrategy(),1999));
cars.Add(new Car(new ToyotaStrategy(),2011);
这将完全满足您的要求。
然而,你会得到策略和汽车之间的耦合。
解决方案2:使用Factory。
Factory 也是一个不错的解决方案,而且可能更容易。您要做的就是拥有一个 CarFactory,其中具有用于创建每种类型汽车的多个工厂方法。
public class CarFactory{
public static Car BuildCorvette(int year){
Car car = new Car(year);
car.Type = "Corvette;
car.Speed = 0.9";
return car;
}
public static Car BuildToyota(int year){
Car car = new Car(year);
car.Type = "Toyota;
car.Speed = 0.5";
return car;
}
}
Usage:
List<Car> cars = new List<Car>();
cars.Add(CarFactory.BuildCorvette(1999));
cars.Add(CarFactory.BuildToyota(2011));
所以这样做的好处是您现在不必担心实例化 Car。它全部由 CarFactory 处理,将您的“实例化逻辑”与代码解耦。但是,您仍然需要知道要构建哪辆车并相应地调用该方法,这仍然是一个小的耦合。
解决方案3:策略工厂!
所以,如果我们想摆脱最后一点耦合,让我们将两者结合在一起!
public class CarFactory{
public static Car BuildCar(CarCreationStrategy strategy, int year){
Car car = new Car(year);
strategy.BuildCar(car);
return car;
}
}
List<Car> cars = new List<Car>();
cars.Add(CarFactory.BuildCar(new CorvetteStrategy(),1999));
cars.Add(CarFactory.BuildCar(new ToyotaStrategy(),2011);
现在你有了一个制造汽车的策略,一个为你制造汽车的工厂,以及一辆没有你原来的额外接头的汽车。太棒了,不是吗?
如果您使用过 Swing,您会注意到这就是它们处理诸如布局之类的一些事情的方式(GridBagLayout、GridLayout 都是策略)。还有一个 BorderFactory。
改进
抽象策略
public interface CarCreationStrategy{
void BuildCar(Car theCar);
}
public class AbstractStrategy:CarCreationStrategy{
public string Type;
public double Speed;
public string Comments;
public void BuildCar(Car theCar){
theCar.Type = this.Type;
theCar.Speed = this.Speed;
theCar.Comments = this.Comments;
}
}
public class CorvetteStrategy extends AbstractStrategy{
public CorvetteStrategy(){
this.Type = "Corvette";
this.Speed = 0.9;
this.Comments = "Speedster!";
}
}
public class ToyotaStrategy extends AbstractStrategy{
public ToyotaStrategy{
this.Type = "Toyota";
this.Speed = "0.5";
this.Comments = "Never dies, even if you drop it from the top of a building";
}
}
使用它可以让您灵活地动态创建 AbstractStrategies(例如,从数据存储中提取汽车属性)。