mercredi 8 mars 2017

How to use Decorator Design in this case?

The following is my test code. The case is: I try to create a view that allows many decorators to be attached on, like scroll bars, extra subviews, backgroundColor, special effect on this view, etc. The problem is I find that i1 and i2 is not what really I need, what I need is whatINeed1 and whatINeed2. In this case, what is the point of having i1 and i2. Don't they become like a generator in this case?

The syntax may be wrong in many places because I tested in objective-c but copied and tailored the java sample code online.

If I am wrong from the beginning, could you please point it out!

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;
}

Aucun commentaire:

Enregistrer un commentaire