Composite Pattern
One-to-one relationship
One-to-many relationship
Example : Command
class Sensor
{
private Command _command;
public void SetCommand(Command cmd)
{
_command = cmd;
}
public void ActEvent()
{
_command.Do();
}
}
class Command
{
public void Do()
{
// Some Action
}
}
Example : Command
class Sensor
{
private List<Command> _commandList;
public void AddCommand(Command cmd)
{
_commandList.Add(cmd);
}
public void ActEvent()
{
foreach (var command in _commandList)
{
command.Do();
}
}
}
Example : Command
class Sensor
{
private Command _command;
public void SetCommand(Command cmd)
{
_command = cmd;
}
public void ActEvent()
{
command.Do();
}
}
class Command
{
public virtual void Do()
{
// Some Action
}
}
class CompositeCommand : Command
{
private List<Command> _commands;
public override void Do()
{
foreach (var command in _commands)
{
command.Do();
}
}
}
Example : Boxes and Products
Example : Boxes and Products
Example : AOCS Simulator
Structure
Applicability
-
When you have to implement a tree-like objects structure
-
When client code don't care about that object is simple or complex elements.
Use the Composite pattern when
Applicability
Adventage
-
Simplify the relation between object.
-
OCP
Cost
-
Complicate composite class.
End.
Composite Pattern
By Jeong Keun Park
Composite Pattern
- 151