我遇到了设计问题,我找不到适当的"解决方案或模式。让我用代码解释一下。
//Mandatory set 1
int minDamage;
int maxDamage;
//Mandatory set 2
int damage;
需要提供强制设置1或强制设置2才能创建此对象。这可以通过两个不同的过载构造器轻松解决。但是,如果我添加这些强制性设置呢?
//Mandatory set 3
int percentageBasedDamage;
我不能拥有包含相同单一数据类型的重载。是的,我可以让最后一个浮动,但如果我添加其他一些强制性设置会发生什么?我最终用完了数据类型。构建器模式似乎没有帮助。我唯一能想到的就是提供所有必需的方法,但这可能最终会出现在一个带有大量参数的构造函数中。此外还不清楚如何使用该物体,我希望它能够做到最小/最大伤害,指定伤害或基于百分比的伤害。
public class MyObject
{
int minDamage;
int maxDamage;
int damage;
int percentageBasedDamage;
public MyObject(int minDamage, int maxDamage, int damage, int percentageBasedDamage)
{
this.minDamage = minDamage;
//...
}
}
MyObject myObject = new MyObject(10, 18, 0, 0); //Correct usage
MyObject myObject = new MyObject(0, 0, 5, 8); //Incorrect usage
Java必须提供一些解决方案。
修改
我实际上对使用构建器模式有很多想法,但无法弄明白。黑暗骑士的回答最终打开了我的眼睛,我想出了这个:
public class Damage extends Action {
String target;
String type;
int minDamage;
int maxDamage;
int damage;
int currentHealthPercentageDamage;
int maxHealthPercentageDamage;
private Damage(Builder build) {
target = build.target;
this.type = build.type;
this.minDamage = build.minDamage;
this.maxDamage = build.maxDamage;
this.damage = build.damage;
this.currentHealthPercentageDamage = build.currentHealthPercentageDamage;
this.maxHealthPercentageDamage = build.maxHealthPercentageDamage;
}
public static class Builder
{
private String target;
private String type;
private int minDamage;
private int maxDamage;
private int damage;
private int currentHealthPercentageDamage;
private int maxHealthPercentageDamage;
public Builder(String target, String type) {
this.target = target;
this.type = type;
}
public Damage minmax(int minDamage, int maxDamage)
{
this.minDamage = minDamage;
this.maxDamage = maxDamage;
return new Damage(this);
}
public Damage damage(int damage)
{
this.damage = damage;
return new Damage(this);
}
public Damage currentHealthPercentageDamage(int currentHealthPercentageDamage)
{
this.currentHealthPercentageDamage = currentHealthPercentageDamage;
return new Damage(this);
}
public Damage maxHealthPercentageDamage(int maxHealthPercentageDamage)
{
this.maxHealthPercentageDamage = maxHealthPercentageDamage;
return new Damage(this);
}
}
由于构建返回损坏的单个"强制设置"已被选中,它现在已经正确设计并清楚了如何对这个类进行实例化和使用。