Page Comparison - Create a decorator (v.15 vs v.16)

Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

Redirect
locationhttps://www.jetbrains.com/help/resharper/2016.1/Create_a_Decorator.html

Note
iconfalse

For more information on the decorator pattern, check out this Wikipedia article.

...

Let’s take an example – suppose you have two objects, called Bird and Lizard, that you want to put into a Decorator:

Code Block
none
none

class Bird
{
  public void Fly()
  {
    ...
  }
}
class Lizard
{
  public void Walk()
  {
    ...
  }
}

...

After we do this for both our classes, we end up with the following code:

Code Block
none
none

internal interface IBird
{
  void Fly();
}
class Bird : IBird
{
  public void Fly()
  {
    ...
  }
}
internal interface ILizard
{
  void Walk();
}
class Lizard : ILizard
{
  public void Walk()
  {
    ...
  }
}
Note
iconfalse

Wiki Markup
{div:class=num}2{div}
Wiki Markup
{div:class=text}Declare a decorator class{div}

With these interfaces, we can make a decorator. First, we declare a class called Dragon, indicating that it implements both IBird and ILizard:

Code Block
none
none

class Dragon : IBird, ILizard
{
  ...
}

Now for the aggregated members. The easiest thing to do is to declare both of these as fields first, i.e.:

Code Block
none
none

class Dragon : IBird, ILizard
{
  private Bird bird;
  private Lizard lizard;
}
Note
iconfalse

Wiki Markup
{div:class=num}3{div}
Wiki Markup
{div:class=text}Use quick-fix to initialize unused fields{div}

Now, we can use ReSharper to initialize both of these fields from constructor parameters:

...

After this, our class will look as follows:

Code Block
none
none

class Dragon : IBird, ILizard
{
  private Bird bird;
  private Lizard lizard;
  public Dragon(Bird bird, Lizard lizard)
  {
    this.bird = bird;
    this.lizard = lizard;
  }
}
Note
iconfalse

Wiki Markup
{div:class=num}4{div}
Wiki Markup
{div:class=text}Generate delegating members for source objects.{div}

And now for the finishing touch – we want to generate delegating members for both bird and lizard. This is easy – we simply open the Generate menu and choose Delegating Members:

...

And here is the end result:

Code Block
none
none

class Dragon : IBird, ILizard
{
  public void Fly()
  {
    bird.Fly();
  }
  public void Walk()
  {
    lizard.Walk();
  }
  private Bird bird;
  private Lizard lizard;
  public Dragon(Bird bird, Lizard lizard)
  {
    this.bird = bird;
    this.lizard = lizard;
  }
}

...