Created
June 19, 2016 20:23
-
-
Save anonymous/3bb00077d497fc3bed872ae4fd5a420a to your computer and use it in GitHub Desktop.
This is an implementaion of multi-command design pattern
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//The Context class minimalized | |
public class CommandContext : IContext | |
{ | |
public IServerController ServerController; | |
public IServcieController ServiceController; | |
//..will have many interfaces as properties | |
public RequiredData Data { get; set; } | |
//Maybe instatiation on constructor is a solution (?) | |
public CommandContext() | |
{ | |
ServerController = new ServerController(); | |
//..will have many interfaces as properties and some are take others at the construction,like: | |
ServiceController = mew ServiceController(ServerController); | |
//.... | |
} | |
} | |
public class RequiredData | |
{ | |
public TheItem Item { get; set; } | |
public RequiredData(TheItem item) | |
{ | |
Item = item; | |
} | |
//will also have many other objects... | |
} | |
interface ICommand | |
{ | |
bool Execute(); | |
void Rollback(); | |
} | |
abstract class BaseCommand : ICommand | |
{ | |
protected CommandContext Context { get; private set; } | |
protected BaseCommand(CommandContext ctx) | |
{ | |
Context = ctx; | |
} | |
} | |
class MultiCommand : BaseCommand | |
{ | |
private List<ICommand> _commands; | |
public MultiCommand(CommandContext ctx, List<ICommand> commands = null) | |
:base(ctx){ | |
SetCommands(commands); } | |
protected override bool RollbackAction() | |
{ | |
foreach (var command in _commands.FastReverse()) | |
{ | |
command.Rollback(); | |
} | |
return true; | |
} | |
protected override ResultObject ExecuteAction() | |
{ | |
if (_commands.Any(command => !command.Execute() )) | |
{ | |
return false; | |
} | |
return true; | |
} | |
//...etc | |
} | |
//Tried this one so far | |
void Run() | |
{ | |
var newData = new RequiredData(vmItem); | |
var ctx = new CommandContext {Data = newData}; | |
var multiCommandGroups = new MultiCommand(ctx); | |
var group1 = new MultiCommand(ctx, new List<ICommand>() | |
{ | |
new Command1(ctx), | |
new Command2(ctx) | |
}); | |
multiCommandGroups.AddCommand(group1); | |
var group2 = new MultiCommand(ctx, new List<ICommand>() | |
{ | |
new Command3(ctx), | |
new Command4(ctx) | |
}); | |
multiCommandGroups.AddCommand(group2); | |
multiCommandGroups.Execute() | |
//I want in every command toable to use Context.Data.whatever and to be updated | |
//And also to Context.ServerControler.doSomething(); etc/ | |
//is this right ?and what about performance.I want the bestpossible approach | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment