我必须做一个至少使用三种设计模式的项目。第一次我尝试使用构建器模式和装饰器模式,但我的老师告诉我应该用复合模式将它们连接起来。我试着想象uml的结构,但它对我来说太难了。有人能帮我吗?如何将它们连接起来?
发布于 2017-06-01 15:16:51
gof说:
装饰器可以看作是只有一个组件的退化的复合体。然而,装饰器增加了额外的职责-它不是用于对象聚合的。
和:
组合(163)是构建者经常构建的。
这是一个带有装饰器的合成图。尝试添加构建器。
package p;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class So44300051 {
static abstract class Component {
Component(String name) {
this.name=name;
}
abstract boolean add(Component component);
abstract boolean remove(Component component);
abstract List<Component> children();
void visit() {
System.out.println(this);
if(this instanceof Decorator1)
((Decorator1)this).additionalBehaviour1();
for(Component child:children())
child.visit();
}
final String name;
}
static class Composite extends Component {
Composite(String name) {
super(name);
}
@Override boolean add(Component component) {
return children.add(component);
}
@Override boolean remove(Component component) {
return children.remove(component);
}
@Override List<Component> children() {
return Collections.unmodifiableList(children);
}
@Override public String toString() {
return "Composite [name="+name+"]";
}
final List<Component> children=new ArrayList<>();
}
static class Leaf extends Component {
Leaf(String name) {
super(name);
}
@Override boolean add(Component component) {
return false;
}
@Override boolean remove(Component component) {
return false;
}
@Override List<Component> children() {
return Collections.emptyList();
}
@Override public String toString() {
return "Leaf [name="+name+"]";
}
}
static abstract class Decorator extends Component {
Decorator(Component component) {
super(component.name);
this.component=component;
}
@Override boolean add(Component component) {
return this.component.add(component);
}
@Override boolean remove(Component component) {
return this.component.remove(component);
}
@Override List<Component> children() {
return this.component.children();
}
@Override public String toString() {
return getClass().getSimpleName()+" "+component;
}
final Component component;
}
static class Decorator1 extends Decorator {
Decorator1(Component component) {
super(component);
}
void additionalBehaviour1() {
System.out.println("additional behaviour 1.");
}
}
public static void main(String[] args) {
Component root=new Composite("root");
root.add(new Leaf("leaf 1"));
root.add(new Decorator1(new Leaf("leaf2")));
root.visit();
}
}发布于 2017-06-01 20:52:19
Design Pattern Combination Image
假设我们有一个复杂的对象,它有许多属性(组件),现在这个组件可以包含其他组件。因此,我们可以使用Builder模式创建这个复杂的对象,得到的对象将是一个组合,现在可以通过使用Decorator设计模式应用额外的职责来进一步修改这个组件
让我们举一个命令的例子,以及一组命令组件--命令扩展组件--比如说一个bat命令echo GroupOfCommand扩展组件--将包含命令列表--比如echo、echo、echo
现在这个组件可以像ComponentBuilder().setCommand("echo").setArgument("hello").setArgument("world").build();一样有多个要传递的参数
装饰器将扩展组件并包含组件,因此Component.execute()方法将成为装饰器的一部分,WrapWithBrackerDecorator execute方法将类似于
public String execute(){
return "(" +component.execute() +")";
}https://stackoverflow.com/questions/44300051
复制相似问题