Defined
The responsibility is dynamically attached to the object. To extend functionality, decorators provide a more resilient alternative than inheritance.
Class diagram
(Image from headfirst design mode)
Java instance
In online games there are usually a variety of weapons, but also by enchanting to the weapon to add a variety of attack effects, now we use decorator mode to achieve this effect.
/** * 武器剑类,武器接口的实现类。对应的ConcreteComponnet类 * @author ZJ */public class Sword implements Weapon{ @Override public void attack() { System.out.println("用剑刺"); }}
/*** 武器剑类,武器接口的实现类。对应的ConcreteComponnet类* @author ZJ*/public class Sword implements Weapon{@Override public void attack() { System.out.println("用剑刺"); }}
/** * 附魔抽象类,对应的Decorator类。 * 实现Weapon接口,是因为武器附魔后还可以当成武器来使用。 * @author ZJ * */public abstract class Enchantment implements Weapon { protected Weapon weapon; //通过构造方法传入需要装饰的对象 public Enchantment(Weapon weapon) { this.weapon = weapon; } //抽象攻击方法,每一个具体的附魔装饰者类都应该有它的实现。 public abstract void attack();}
/** * 火属性附魔类。对应途中ConcreteDecorator类 * 这是一个具体的装饰者实现类 * @author ZJ * */public class EnchantingWithFire extends Enchantment{ public EnchantingWithFire(Weapon weapon) { super(weapon); } //实现具体的攻击方法 public void attack() { // TODO Auto-generated method stub System.out.print("火属性攻击特效--------"); weapon.attack(); }}
public class Test { public static void main(String[] args) { // TODO Auto-generated method stub Weapon sword = new Sword(); Weapon fireSword = new EnchantingWithFire(sword); sword.attack(); fireSword.attack(); }}输出结果:用剑刺火属性攻击特效--------用剑刺
After reading the above example, you may think why so troublesome, write a bunch of interfaces and classes, I directly write a fire attribute attack effect of the sword class and a common sword class just fine. Indeed in our above example may be directly written two classes is a better way but in online games, weapons can not only sword one, there may be any leaning sword, Dragon Sword, hit dog sticks, kill pig knives and so on. Enchanted properties may also have light, ice, fire and so on, so the direct way to write a class is to write the light properties of the day sword, ice properties of the day sword, fire properties of the sword equivalent to the number of weapon types * The number of enchanted species of the class of classes and our example of the implementation of only the number of weapons and the number of enchantments And every weapon we add, we just need to add a generic weapon class, so we don't have to consider the various enchantments.
Other
For decorator mode, you can refer to the Java IO Class library for more information.
Github:https://github.com/panici4/designpattern/tree/master/decorator
Java design pattern 02-Decorator Mode