Foreword
Decorative patterns, refers 动态
to add some additional responsibilities to an object, you add functionality, the decorative pattern is more flexible with respect to subclass it.
Scene introduced
A person, behavior is sleep eat and drink, and now we want to make this man to become Superman, that has functions to save the world.
Abstract decorator AbstractDecorator
has an abstract class AbstractPerson
subclass object, and can AbstractPerson
subclass object is modified.
So no modifications person
under the circumstances to achieve the specific class, modified into ConcreteSuperPersonDecorator
class
1. abstract class 人
/**
* @author 阳光大男孩!!!
*/
public abstract class AbstractPerson {
/**
* 动作
*/
abstract void action();
}
2. Human implementation class
/**
* @author 阳光大男孩!!!
*/
public class ConcretePerson extends AbstractPerson{
@Override
void action() {
System.out.println("吃...睡...");
}
}
3. decorative abstract class
/**
* @author 阳光大男孩!!!
*/
abstract class AbstractDecorator extends AbstractPerson {
/**
* 被装饰的对象
*/
protected AbstractPerson abstractPerson;
public void setPerson(AbstractPerson abstractPerson) {
this.abstractPerson = abstractPerson;
}
@Override
void action() {
if(abstractPerson!=null)
{
abstractPerson.action();//实际上执行的是abstractPerson的action()方法
}
}
}
This abstract class subclass can be other classes 装饰
.
4. decorator abstract class implementation class
/**
* @author 阳光大男孩!!!
*/
public class ConcreteSuperPersonDecorator extends AbstractDecorator{
@Override
void action() {
super.action();
System.out.println("拯救世界...");
}
}
5. Test
/**
* @author 阳光大男孩!!!
*/
public class Main {
public static void main(String[] args) {
//普通人吃和睡
ConcretePerson person = new ConcretePerson() ;
person.action();
System.out.println("在不改动普通人类的情况下,增加新的功能:");
ConcreteSuperPersonDecorator csd = new ConcreteSuperPersonDecorator();
csd.setPerson(person);
csd.action();
}
}
operation result
吃...睡...
在不改动普通人相关类的情况下,增加新的功能:
吃...睡...
拯救世界...
to sum up
Decorators need only care about their functions, without the need to be concerned about how the new functions are added to the object in the chain.