2017-03-08 31 views
0

以下是我的测试代码。情况是:我尝试创建一个允许附加许多装饰器的视图,例如滚动条,额外的子视图,backgroundColor,这个视图上的特殊效果等等。问题是我发现i1i2不是真正的我需要,我需要的是whatINeed1whatINeed2。在这种情况下,i1i2有什么意义。在这种情况下,它们不会像发电机一样吗?如何在这种情况下使用装饰设计?

在许多地方,语法可能是错误的,因为我在objective-c中测试过,但在线复制和定制了java示例代码。

如果我从一开始就错了,请您指出!

public class Decorator { 

abstract class I implements DefaultView { I render(); } 

static class A implements I { public I render() { System.out.print('A'); } } 

static abstract class D implements I { 
    private I core; 
    public D(I inner) { core = inner; } 
    public I render() { return core.render(); } 
} 

static class X extends D { 
    public X(I inner) { super(inner); } 
    public I render() { 
     I i = super.render(); 
     i.setBackgroundColor(); 
    } 
} 

static class Y extends D { 
    public Y(I inner) { super(inner); } 
    public I render() { 
     I i = super.render(); 
     View v = new View(); 
     //This is objective-c similar syntax, 
     //I don't know what's equivalent to Java 
     i.addSubview(v); 
    } 
} 

public static void main(String[] args) { 
    I i1 =new X(new A()) 
    I i2= new Y(new X(new A()))}; 
    I whatINeed1 = i1.render(); 
    I whatINeed2 = i2.render; 
} 

浅谈装饰设计是添加额外的功能,而无需修改现有的代码。我如何实现下面显示的模型?如何在不修改源代码的情况下绘制边框和滚动条?滚动条需要与原始窗口进行交互。 enter image description here

回答

1

装饰通常是用来添加额外的“功能”的类X(方法假设),而无需修改X的源代码

public class PlayerScore{ 
    void setScore(int); 
} 

我们要添加方法,使我们能够在阶梯中得分,但我们不能/不想修改PlayerScore。然后:

public class MyPlayerScore extends PlayerScore{ 
    PlayerScore component; 

    int getRank() { /**some code**/} 
    void setScore(int x){ component.setScore(x);} 

} 

通过您的代码的外观,您实际上不添加功能。基类I已经具有setBackgroundColor(),addSubView()等功能,您只需在子类中调用它们即可。

这看起来像是继承和组合模式的混合体,而不是装饰器,即使构图部分(通过将构件传递给构件)使它看起来像装饰器。

如果你的代码适合你,但是你的代码没问题,但是如果你想使用Decorator模式,你需要为继承类添加越来越多的方法,因为你需要为这些类获得更多和更专门的行为(class PanelView将添加例如空卷轴())

更多信息的装饰:https://en.wikipedia.org/wiki/Decorator_pattern

EDIT(1):

要使用装饰的滚动条添加到父视图,一个窗口让我们说,父类必须公开某种形式新的Decorated类可以用来实现滚动行为的接口。例如,如果窗口有一个返回的句柄一些图形API的方法,让我们把手柄“G”,然后是装饰类的ScrollPane可以做到以下几点:

public class ScrollPane extends Window{ 
    Window component; 
    void renderScrollBar(){ 
     Graphics g = window.getGraphicsHandle(); 
     g.drawRectangle(/** some coords for where to put the bar **/); 
     /** some extra code to add logic on the scroll bar, 
     /** such as shifting the Window content up or down and cull out 
     /** the portion that is outside of the ScrollPane. 
     /** For example, openGL could allow you to do this with scissor 
     /** test **/ 
    } 

    void render(){ 
     component.render(); 
     this.renderScrollPane(); 
    } 
} 

https://www.khronos.org/opengl/wiki/Scissor_Test如果你有兴趣在评论的最后部分。

这是你如何去做。很明显,实现一个运行良好的滚动窗格可能需要更多的思考,但在布局类架构方面,Decorator模式可以很好地为您设计GUI。

+0

Thx用于评论,re'Decorator通常用于为X类(方法可以说)添加额外的“特性”,而不修改X的源代码.',我编辑了我的问题,你能帮我回答? –