我问了一个问题关于使用策略模式和LSP的问题,但是答案参差不齐,从长远来看,这不是个好主意。然而,在我的问题末尾有一条评论说,虽然我没有违反界面分离原理,但我违反了LSP
客户端不应该被迫实现他们不使用的接口。而不是一个fat接口,许多小接口是首选的基于方法组,每个为一个子模块服务。
假设我有一个这样的武器类:
public final Weapon{
private final String name;
private final int damage;
private final List<AttackStrategy> validactions;
private final List<Actions> standardActions;
public Weapon(String name, int damage, List<AttackStrategy> standardActions, List<Actions> attacks)
{
this.name = name;
this.damage = damage;
standardActions = new ArrayList<Actions>(standardActions);
validAttacks = new ArrayList<AttackStrategy>(validActions);
}
public void standardAction(String action){} // -- Can call reload or aim here.
public int attack(String action){} // - Call any actions that are attacks.
}接口和实现:
public interface AttackStrategy{
void attack(Enemy enemy);
}
public class Shoot implements AttackStrategy {
public void attack(Enemy enemy){
//code to shoot
}
}
public class Strike implements AttackStrategy {
public void attack(Enemy enemy){
//code to strike
}
}使用:
List<AttackStrategy> actions = new ArrayList<AttackStrategy();
actions.add(new Shoot())
List<Actions> standardActionactions = new ArrayList<Actions>();
actions.add(new Reload(10))
Weapon rifle = new Weapon("Sniper Rifle", 5, standardActionactions, actions);
List<AttackStrategy> actions = new ArrayList<AttackStrategy();
actions.add(new Swing())
List<Actions> standardActionactions = new ArrayList<Actions>();
actions.add(new Drop())
Weapon sword = new Weapon("Standard Sword", 10, standardActionactions, actions);我有两种武器,两种武器的行为都不一样,两者都可以用来攻击,但每种类型都有不同的行动。例如,Sword 不应该是,而且根据我的集合的逻辑,无论如何都不能调用或实现重载。
在我的文本冒险游戏中,如果您将“重新加载”传递给sword.standardAction("reload"),内部逻辑将检查列表是否包含一个重新加载对象,如果包含,则执行,如果没有,则武器无法使用,因此不能,因此它忽略它。
我是否违反了ISP?
我的剑永远不会实现reload,除非客户机决定实现它,否则我不会强迫客户端接受Sword知道他们永远不会使用的Reload方法。
发布于 2017-10-24 02:42:04
听起来武器抽象概念有点过于笼统了。我会把它分解成更小的抽象
- attack
- aim
- reload
- attack (throws OutOfBulletException)
- attack (throws CallousesOnHandHurtException after 100 hits without lotion)
- applyLotion
- attack (throws SomebodyElseCaughtMyBoomerangException, and then ImHosedException after that)
https://stackoverflow.com/questions/46893229
复制相似问题