Chain of Responsibility
This commit is contained in:
31
design-pattern/src/ChainOfResponsibility2/Application.java
Normal file
31
design-pattern/src/ChainOfResponsibility2/Application.java
Normal file
@@ -0,0 +1,31 @@
|
||||
package ChainOfResponsibility2;
|
||||
|
||||
public class Application {
|
||||
public static void main(String[] args) {
|
||||
Attack attack = new Attack(100);
|
||||
|
||||
Armor armor1 = new Armor(10);
|
||||
Armor armor2 = new Armor(15);
|
||||
|
||||
armor1.setNextDefense(armor2);
|
||||
|
||||
armor1.defense(attack);
|
||||
|
||||
System.out.println(attack.getAmount());
|
||||
|
||||
Defense defense = new Defense() {
|
||||
@Override
|
||||
public void defense(Attack attack) {
|
||||
int amount = attack.getAmount();
|
||||
attack.setAmount(amount-=50);
|
||||
}
|
||||
};
|
||||
|
||||
armor2.setNextDefense(defense);
|
||||
|
||||
attack.setAmount(100);
|
||||
armor1.defense(attack);
|
||||
|
||||
System.out.println(attack.getAmount());
|
||||
}
|
||||
}
|
||||
36
design-pattern/src/ChainOfResponsibility2/Armor.java
Normal file
36
design-pattern/src/ChainOfResponsibility2/Armor.java
Normal file
@@ -0,0 +1,36 @@
|
||||
package ChainOfResponsibility2;
|
||||
|
||||
public class Armor implements Defense{
|
||||
|
||||
private Defense nextDefense;
|
||||
private int def;
|
||||
|
||||
public Armor() {
|
||||
}
|
||||
|
||||
public Armor(int def) {
|
||||
this.def = def;
|
||||
}
|
||||
|
||||
public void setDef(int def) {
|
||||
this.def = def;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void defense(Attack attack) {
|
||||
process(attack);
|
||||
if(nextDefense != null) {
|
||||
nextDefense.defense(attack);
|
||||
}
|
||||
}
|
||||
|
||||
private void process(Attack attack) {
|
||||
int amount = attack.getAmount();
|
||||
amount -= def;
|
||||
attack.setAmount(amount);
|
||||
}
|
||||
|
||||
public void setNextDefense(Defense nextDefense) {
|
||||
this.nextDefense = nextDefense;
|
||||
}
|
||||
}
|
||||
18
design-pattern/src/ChainOfResponsibility2/Attack.java
Normal file
18
design-pattern/src/ChainOfResponsibility2/Attack.java
Normal file
@@ -0,0 +1,18 @@
|
||||
package ChainOfResponsibility2;
|
||||
|
||||
public class Attack {
|
||||
|
||||
private int amount;
|
||||
|
||||
public Attack(int amount) {
|
||||
this.amount = amount;
|
||||
}
|
||||
|
||||
public int getAmount() {
|
||||
return amount;
|
||||
}
|
||||
|
||||
public void setAmount(int amount) {
|
||||
this.amount = amount;
|
||||
}
|
||||
}
|
||||
6
design-pattern/src/ChainOfResponsibility2/Defense.java
Normal file
6
design-pattern/src/ChainOfResponsibility2/Defense.java
Normal file
@@ -0,0 +1,6 @@
|
||||
package ChainOfResponsibility2;
|
||||
|
||||
public interface Defense {
|
||||
|
||||
public void defense(Attack attack);
|
||||
}
|
||||
Reference in New Issue
Block a user