Decorator design pattern is to enhance the function of a specific category. For example, before the original or was added after the number of operations, etc.. The introduction of the succession of the problem can be solved, that is, through the use of heavy-duty sub-class to achieve. The benefits of the introduction of inheritance, as well as the shortcomings of the introduction of inheritance, and the Decorator pattern is to solve the shortcomings of the succession and students.
There is an example:
Simulation developers here, we are most familiar with one of the scenes: the field of software engineering, human resources.
Look at the map:
Engineer is an interface.
package org.forefficiency.pattern.decorator;
public interface Engineer {
public void doCodding();
}
Coder is a code of workers, there are functions to write code: doCodding () method.
package org.forefficiency.pattern.decorator;
public class Coder implements Engineer
{
public void doCodding() {
System.out.println("--I am codding!");
}
}
Now found that not enough manpower, and require workers to write the code before the code design, or writing the code to write the document.
Then add a Coder brothers: MultiRoleEngineer.
package org.forefficiency.pattern.decorator;
public class MultiRoleEngineer implements Engineer{
protected Engineer coder;
public void doCodding() {
doDesign();
coder.doCodding();
doFile();
}
public MultiRoleEngineer(Engineer cod)
{
this.coder = cod;
}
public void doDesign()
{
System.out.println("--I am doing design!");
}
public void doFile()
{
System.out.println("--I am doing file work!");
}
}
Both MultiRoleEngineer and Coder Interface Engineer.
Note MultiRoleEngineer itself a member of Engineer property, through the constructor to initialize the attributes.
package org.forefficiency.pattern.decorator;
public class DesignCode extends MultiRoleEngineer {
public DesignCode(Engineer cod) {
super(cod);
}
public void doCodding() {
doDesign();
coder.doCodding();
}
public void doDesign() {
System.out.println("--I am doing design!");
}
}
package org.forefficiency.pattern.decorator;
public class CodeFile extends MultiRoleEngineer
{
public CodeFile(Engineer cod)
{
super(cod);
}
public void doCodding() {
coder.doCodding();
doFile();
}
public void doFile()
{
System.out.println("--I am doing file work!");
}
}
Test:
package org.forefficiency.pattern.decorator;
public class Test {
public static void main(String[] args)
{
Engineer cod = new Coder();
Engineer designCoder = new DesignCode(cod);
designCoder.doCodding();
designCoder = new CodeFile(cod);
designCoder.doCodding();
}
}
Results:
run: --I am doing design! --I am codding! --I am codding! --I am doing file work! 成功生成(总时间:0 秒)







