Anda di halaman 1dari 24

IEG 3080

Tutorial 9
Prepared by Wilson
Outline
 Design Patterns
 Creational Patterns
 Structural Patterns
 Behavioral Patterns

 Project Phase 2
Design Patterns

Creational Structural Behavioral


Abstract Factory Adapter Chain of Resp.
Builder Bridge Command
Factory Method
Composite Interpreter
Prototype
Decorator Iterator
Singleton
Façade Mediator
Flyweight Memento
Proxy Observer
State
Strategy
Template
Visitor
Design Patterns
 Chain of Responsibility
 Avoid coupling the sender of a request to its
receiver. Chain the receivers and pass the
request along the chain until the request is
handled.
Receiver1
Request HandleRequest() Receiver2

HandleRequest() Receiver3

HandleRequest()

 Example: Exception Handling


Design Patterns
 Chain of Responsibility successor

// The abstract "Handler“ class


abstract class Handler Handler
{ HandleRequest ()
protected Handler successor;

public void SetSuccessor(Handler successor)


{
this.successor = successor;
} ConcreteHandler1 ConcreteHandler2

HandleRequest () HandleRequest ()
public abstract void HandleRequest(int request);
}

// The "ConcreteHandler1“ class // The "ConcreteHandler2“ class


class ConcreteHandler1 : Handler class ConcreteHandler2 : Handler
{ {
public override void HandleRequest(int request) public override void HandleRequest(int
{ request)
if (request >= 0 && request < 20) {
{ if (request >= 20 && request < 40)
Console.WriteLine("{0} handled request {
{1}", Console.WriteLine("{0} handled request
this.GetType().Name, request); {1}",
} this.GetType().Name, request); Forward the request
else if (successor != null) } to next handler
{ else if (successor != null)
successor.HandleRequest(request); {
} successor.HandleRequest(request);
} }
Design Patterns
 Chain of Responsibility
static void Main()
{
// Setup Chain of Responsibility
Handler h1 = new ConcreteHandler1();
Handler h2 = new ConcreteHandler2();
h1.SetSuccessor(h2);

// Generate and process request


int[] requests = {5, 8, 4, 16, 24, 31, 27, 33};

foreach (int request in requests)


{
h1.HandleRequest (request);
}
}
Design Patterns
 Command
 Encapsulate a request as an object. Allowing a
request to be handled in the same way as an
object item and to be parameterized.
Invoker Command
Execute()

ConcreteCommand
Receiver receiver
Execute() receiver
Action() Action()

 Example: delegate in C#
Design Patterns
 Command Parameterize the command
by compositing different
  // The abstract "Command“ class  concrete receiver
  abstract class Command 
  {
    protected Receiver receiver;

    public Command(Receiver receiver)

Command
    {
      this.receiver = receiver;
    }
Execute()
    public abstract void Execute();
  }

  // The "ConcreteCommand“ class
  class ConcreteCommand : Command
  {
    public ConcreteCommand(Receiver receiver) : base(receiver) 
    {  }
ConcreteCommand
    public override void Execute()
    {
      receiver.Action();
Execute() receiverAction()
    }
  }
Action is performed
for the compositing
receiver
Design Patterns
 Command
  // "Receiver"
  class Receiver  The method that Receiver
  { will finally be
    public void Action()
    { called. Action()
      Console.WriteLine(“Actual action to perform");
    }
  }

  // "Invoker"
  class Invoker 
  {
    private Command command;

    public void SetCommand(Command command)
    {
      this.command = command;
    }
Invoker
    public void ExecuteCommand()
    {
      command.Execute(); Accepting command
    }     and invoking command.
  }
Design Patterns
 Command

aReceiver aClient aCommand anInvoker


new Command(aReceiver)

StoreCommand(aCommand)

Execute()

Action()
Design Patterns
 Interpreter
 Given a language, define a representation for
its grammar along with interpreter that uses
the representation to interpret sentences in the
language.
AbstractExpression
Interpret(Context)

TerminalExpression NonterminalExpression
Interpret(Context) Interpret(Context)
Design Patterns
 Interpreter
  // "AbstractExpression" 
  abstract class AbstractExpression 
AbstractExpression
  {
    public abstract void Interpret(Context context); Interpret(Context)
  }

  // "TerminalExpression"
  class TerminalExpression : AbstractExpression
  {
    public override void Interpret(Context context)   TerminalExpression NonterminalExpression
    {
      Console.WriteLine("Called Terminal.Interpret()"); Interpret(Context) Interpret(Context)
    }
  }

  // "NonterminalExpression"
  class NonterminalExpression : AbstractExpression Should filled with interpret
  { operations with respect to
    public override void Interpret(Context context)  
    {
the expression class
      Console.WriteLine("Called Nonterminal.Interpret()");
    }  
  }
}
Design Patterns
 Iterator
 Provide a way to access the elements of an
aggregate object sequentially without exposing
its underlying representation.
List ListIterator
First()
Next()
IsDone()
CurrentItem()

index

 Example: the interface IEnumerator in C#


Design Patterns
 Iterator   // “ListIterator"
// “List”   class ListIterator
class List    {
 {     private List aggregate;
    private ArrayList items = new ArrayList();     private int current = 0;

    public override ListIterator CreateIterator()  {     // Constructor 
      return new ListIterator(this);     public ListIterator(List  aggregate)   {
    }       this.aggregate = aggregate;
    }
 } The actual aggregate
instance     public virtual object First()  {….}
    public virtual object Next()  {….}
hides inside the iterator
    public virtual object CurrentItem() {….}
    public virtual bool IsDone() {….}
  }

The only exposed


interfaces
   
Design Patterns
 Mediator
 Define an object that encapsulates how a set
of objects interact.
Colleague
Colleague
Colleague

Mediator

Colleague
Design Patterns
 Mediator

mediator
Mediator Colleague

ConcreteMediator

ConcreteColleague1

ConcreteColleague2
Design Patterns
 Mediator
 // "Mediator"    public override void Send(string message, 
  abstract class Mediator       Colleague colleague) Centralize control
  {     { On objects interaction
    public abstract void Send(string message,        if (colleague == colleague1)
      Colleague colleague);       {
  }         colleague2.Notify(message);
      }
  // "ConcreteMediator"        else
  class ConcreteMediator : Mediator       {
  {         colleague1.Notify(message);
    private ConcreteColleague1 colleague1;       }
    private ConcreteColleague2 colleague2;     }
  }
    public ConcreteColleague1 Colleague1
    { Mediator
      set{ colleague1 = value; }
    } Reference is kept for
message forwarding
    public ConcreteColleague2 Colleague2
    {
      set{ colleague2 = value; }
    }
ConcreteMediator
  
Design Patterns
Mediator
public void Send(string message)
     {
      mediator.Send(message, this);
    }
  // "Colleague" 
  abstract class Colleague
    public void Notify(string message)
  {
    {
    protected Mediator mediator;
      Console.WriteLine("Colleague1 gets message: " 
        + message);
    // Constructor 
    }
    public Colleague(Mediator mediator)
  }
    {
      this.mediator = mediator;
  // "ConcreteColleague2" 
    }
  class ConcreteColleague2 : Colleague
  }
  {…………..}
  // "ConcreteColleague1" 
  class ConcreteColleague1 : Colleague
  { Colleague
    // Constructor 
    public ConcreteColleague1(Mediator mediator) 
      : base(mediator) 
    { 
    }

    
ConcreteColleague1 ConcreteColleague2
Design Patterns
 References
 Gamma, Erich et al, “Design Patterns:
Elements of Reusable Object-Oriented
Software,” Addison-Wesley.
 Design Patterns with C# sample code: http://
www.dofactory.com/Patterns/Patterns.aspx
Project Phase 2
 You are required to implement:
 Game controlling functions
 Movement
 Harpoon shooting

 Collision detection functions


 Between main character and ball
 Between ball and harpoon
Project Phase 2
 Game controlling functions
 Movement:
public class Form1 {
Register an eventhandler
………
to KeyDown event
public Form1() {
……
this.KeyDown +=
new System.Windows.Forms.KeyEventHandler(this.MyKeyDown);
}
…………
public void MyKeyDown(object sender,
System.Windows.Forms.KeyEventArgs e)
{
string k = e.KeyData.ToString();
if (k.Equals(“Right”)) { Get the pressed key and
main_char.x += 5; changes the position
} of the main character
else if (k.Equals(“Left”)) {
main_char.x -=5;
}
}
}
Project Phase 2
 Game controlling functions
 Harpoon shooting:
public class Form1 {
// bullets object container
BulletContainer bullets = new BulletContainer();
…………
public void MyKeyDown(object sender,
System.Windows.Forms.KeyEventArgs e)
{
string k = e.KeyData.ToString();
…… Create a harpoon after
// press space to shoot bullet pressing shooting key
else if (k.Equals(“Space”)) {
Bullet b = new Bullet();
bullets.add(b);
} Update the existing
} harpoons in the game
…………….. scene
private void timer1_Tick(object sender, EventArgs e) {
…………
foreach (Bullet b in bullets) { b.update(); }
}
Project Phase 2
 Game controlling functions
 Harpoon shooting:
public class Bullet {
private int height;
…………
public Bullet() {
height = 0;
}
public void update() {
height += 10;
}
……………
public void draw(Graphics g) {
…..// draw a harpoon figure by the value of height
}
}
Project Phase 2
 Collision detection functions
 Between main character and ball
 Between ball and harpoon

 Make uses of intersectsWith (.) method


from Rectangle class. E.g. basic form of
intersection detection is:
Rectangle aRectangle1 = new Rectangle();
Rectangle aRectangle2 = new Rectangle();

// checking whether two rectangle area overlapped


aRectangle1.intersectsWith(aRectangle2);

Anda mungkin juga menyukai