I can't explain my problem in English. so let me show my situation.
// in Main Project
public class User
{
public int version
{
get;
set;
}
}
// in Common Project
public class Service : BaseService
{
User _user;
public void SetVersion(int versionID)
{
_user.version = versionID;
}
public bool HasMessage()
{
return GetMessage(user.version);
}
}
And now I have another sub project. and I need use Service class in there.
so I wish make Service class independent from User class.
how do I do that?
I have only below solution. Is there any brilliant way?
public class Service : BaseService
{
Action<int> _getCallBack;
Func<int> _setCallBack;
public Service(Action<int> getCallback, Func<int> setCallBack)
{
_getCallback = getCallback;
_setCallback = setCallback;
}
public void SetVersion(int versionID)
{
setCallback(versionID);
}
public bool HasMessage()
{
return GetMessage(getCallback())
}
}
It depends on your use of 'User' in service.
You can add an interface IUser in Common project, and have User implement it.
Then in the other SubProject, write UserSub : IUser that also implements the interface IUser.
That way Service is independent, but you'll still have to implement something in each project that uses Service. (Which you need to do anyway, because Service currently uses it as an inner variable.
Yes there are several best practices which allow decoupling components, they are called design patterns. I would recommend to take a look at all of them to decide which one fits your context best. All of them have advantages and disadvantages, application scope and impact. There is no one brilliant solution for decoupling.
I think the command pattern can be the right one for your problem.
See: http://www.dofactory.com/net/design-patterns
and https://csharpdesignpatterns.codeplex.com
Related
Hey i am working as software developer and starting to understand design pattern, please give me the concept about the bridge and decorator pattern. Already I have gone through the previous post of the related topic but i am not cleared about that please help me!!.
First of all we need to know what is the meaning of Bridge and Decorator pattern??
Bridge: The GOF definition of Bridge pattern is "Decouple an abstraction from its implementation so that the two can vary independently". and this pattern is fall under structural design pattern, why structural because you are changing the structure of our application.
Let's analysis this : Let you implement a business Logic
Class Business
{
public void Operation()
{
//you business logic here
}
}
Class Client
{
Business b=new Business();
b.Operation();
}
please consider in the above "Business" class, is for your application structure that you have implemented and with this structure your client is happy.
Now say after One year your client is requesting you to change their business operation structure as well as previous implemented operational structure remain same for some clients. Now what you will do?
Lets see
Class Business
{
public void Operation()
{
//you business logic here
}
public void NewOperation()
{
//you New business logic here
}
}
Class Client
{
Business b=new Business();
b.NewOperation();
}
Now assume how many changes you need to done for new operation.
Here bridge pattern help a lot;
interface IOperation
{
void operation();
}
public class ConcreteOPeration:Ioperation
{
void operation
{
//you code
}
}
public class NewConcreteOPeration:Ioperation
{
void operation
{
//you new code code
}
}
Public interface OperationBridege
{
void callOperation();
}
Public Class ConcreteBridge:OperationBridege
{
private Ioperation _ioperation;
public ConcreteBridge(Ioperation _operation )
{
this._ioperation=_operation;
}
void callOperation()
{
this._ioperation.operation();
}
}
class client
{
//Ioperation oprtn =New ConcreteOPeration();//NewConcreteOPeration
//if you change to new operation need know change just
the new concreteOperation class
Ioperation oprtn =New NewConcreteOPeration();
OperationBridege bridege =new ConcreteBridge(oprtn);
bridege.callOperation();
}
Any where you using this operation nothing impacted in your application for structural changes for this pattern fall under structural design pattern.
Now we discuss about Decorator pattern.
Decorator: The GoF definition is "Attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality."
Lets analysis this if you want to add some additional facilities dynamically in your previously implemented class then GOF suggested at this situation we will must use decorator design pattern.
Let see an example
public interface IComponent
{
void Operation();
}
public class ConcreteComponent:IComponent
{
public void Operation()
{
Console.WriteLine("This is the main functionality!!!");
}
}
public class Decoretor:IComponent
{
protected IComponent component;
public void SetComponent(IComponent _component)
{
this.component = _component;
}
public virtual void Operation()
{
component.Operation();
}
}
public class ConcreteDecoratorA : Decoretor
{
public override void Operation()
{
base.Operation();
}
}
public class ConcreteDecoratorB : Decoretor
{
public override void Operation()
{
base.Operation();
Show();
}
public void Show()
{
Console.WriteLine("Additional resposiblity attached");
}
}
class Program
{
static void Main(string[] args)
{
IComponent c = ComponentObjCreator.ComponentCreator();
//Decoretor d = new ConcreteDecoratorA();//In this class have basic //functionalities
Decoretor d = new ConcreteDecoratorB();//in this class has some additional
functionalities
d.SetComponent(c);
d.Operation();
}
}
Actually here we decorated our application structure with some new functionalities
and we are implemented in the "ConcreteDecoratorB" class that's why we are called this decorator business pattern.it's also fall under structural design pattern.
I have found Christopher Okhravi a YouTube VLogger to have posted some interesting videos about various design patterns, including Bridge & Decorator.
He does so in a quite entertaining (considering the subject) and presents it in a fairly easy to understand manner.
Decorator Pattern:
https://youtu.be/GCraGHx6gso
Bridge Pattern:
https://youtu.be/F1YQ7YRjttI
You can also check out this website:
https://www.oodesign.com/
Both of them are in the structural patterns category in the Gof.
we use the Bridge Pattern when we need to have some separated logic that when we need to use each of them. for example, you have software to send multiple types of notification to users like SMS, Email and sets. here we use the Bridge Pattern.
On the other hand when we need to implement a system to add some specific behavior to object we use a Decorator pattern. For example, you decide to make an IceCream Machine with multiple choosable things like Honey, Bread, nuts and ... here we use the Decorator pattern (Also known as Wrapper).
There is some useful information on below links
Decorator Design Pattern
Bridge Deign Pattern
I'm trying to write code as better I can, for that reason looking at some code I wrote in past I've seen that I access to .config appsetting with something as
Public void Do()
{
Var x = ConfigurationManager.AppSettings.Get("foo");
doSomethingElse(x);
}
Writing test on this method I asked myself wasn't it better to have an interface with properties that exposes all the .config AppSettings values ? This would allow me to replace via IoC the real implementation.
on the other side I ask is it correct to wrap all those values in a class/interface?what if I've different assemblies that compose an application and I need to access to that object? Supposed that it will be in a shared project does it make sense to have a value as
Int ModelAvalue {get{};}
Defined in that class that would never be used in ModelB?
Configuration is a dependency. I think your idea about creating an interface that returns the most appropriate type helps both with testing and makes your code easier to understand. It also gives you the flexibility to change where your configuration is stored in the future.
To answer your other question, it would be better to have interfaces smaller and more specific, as per the interface segregation principle. You could have different interfaces in which each interface is a group of closely related settings. For example, you would not have an interface that has your database connection string and your log file path.
public interface IDatabaseConfiguration
{
string ConnectionString { get; }
}
public interface IBlogConfiguration
{
int NumberOfPostsPerPage { get; }
}
public class AppConfiguration : IDatabaseConfiguration, IBlogConfiguration
{
public string ConnectionString
{
get { return ConfigurationManager.ConnectionStrings["MyDb"].ConnectionString; }
}
public int NumberOfPostsPerPage
{
get { return int.Parse(ConfigurationManager.AppSettings["PostsPerPage"]); }
}
}
In the future, if you decide that NumberOfPostsPerPage should be stored elsewhere, you can create a different concrete implementation of IBlogConfiguration
I'm working on a game that uses MVCS and has, so far, clearly separated the business logic from the view.
However, I've been having trouble with one particular piece of the puzzle.
In the game we have command classes (IPlayerCommand) that execute a specific business logic. Each command class returns a result class (PlayerCommandResult). For each PlayerCommand we have a respected visual command class (IVisualPlayerCommand) that takes the PlayerCommandResult and updates the view accordingly.
I'd like the IVisualPlayerCommand to use specific classes that inherit PlayerCommandResult in order to get the information it needs (as opposed to using object). I'd also like to make it compile-time safe (as opposed to casting it before using it). For these two reasons I made the classes use generics.
Here are the declaration of the classes:
public class PlayerCommandResult
{}
public interface IPlayerCommand<T> where T : PlayerCommandResult
{
T Execute(GameWorld world);
}
public interface IVisualPlayerComamnd<T> where T : PlayerCommandResult
{
void Play(T commandResult);
}
Here is the Move Unit command as an example:
public class MoveUnitPlayerCommand : IPlayerCommand<MoveUnitPlayerCommandResult>
{
private Unit unitToMove;
public MoveUnitPlayerCommand(Unit unit)
{
this.unitToMove = unit;
}
public MoveUnitPlayerCommandResult Execute(GameWorld world)
{
MoveUnitPlayerCommand result = new MoveUnitPlayerCommand();
// Do some changes to the world and store any information needed to the result
return result;
}
}
public class MoveUnitVisualPlayerCommand : IVisualPlayerCommand<MoveUnitPlayerCommandResult>
{
void Play(MoveUnitPlayerCommandResult commandResult)
{
// Do something visual
}
}
public class MoveUnitPlayerCommandResult : PlayerCommandResult
{
public Unit TargetUnit { get; private set; }
public Path MovePath { get; private set; }
}
So far, so good. However, I'm having a really hard time tying a IPlayerCommand to a IVisualPlayerCommand because of the use of generics:
public class CommandExecutorService
{
public void ExecuteCommand<T>(IPlayerCommand<T> command) where T : PlayerCommandResult
{
T result = command.Execute(world);
IVisualPlayerCommand<T> visualCommand = GetVisualPlayerCommand(command);
visualCommand.Play(result);
}
public IVisualPlayerCommand<T> GetVisualPlayerCommand<T>(IPlayerCommand<T> command) where T : PlayerCommandResult
{
// ?!?!?!?!?!??!?!?!??!?!
}
}
I have a feeling that what I'm trying to do is not even possible because of the way generics work in C# (as opposed to Java where I could say IVisualPlayerCommand<?>).
Could you help me figure out a way?
Any feedback for the design is welcome.
P.S. Sorry if the title doesn't reflect the question. I wasn't sure how to boil down the question in one line.
P.P.S. Which is why I also don't know if this question has been asked and answered before.
You two command classes, are served as service. To me, for this case, I would use the service locator pattern. As how to implement this pattern, you can check this link
The drawback of using template, is that, if something changes, you have to compiled it again.
Here's link which provides an example of the service locator pattern.
So for you code, you want find the corresponding instance of IVisualPlayerCommand to IPlayerCommand, so the concrete service can inherit from both interface, which it actually implements the IVisualPlayerCommand interface, while the IPlayerCommand just severs as a tag.
so the code will like this:
class MoveUnitVisualPlayerCommand: IVisualPlayerCommand, IPlayerCommand {}
services = new Dictionary<object, object>();
this.services.Add(typeof(IPlayerCommand ), new MoveUnitVisualPlayerCommand());
as how to get the service, you can refer the example.
Hope this helps.
I am working in a content management system that uses C# and allows for adding separate code in a central class. One issue that has come up is we would like to have a separate code base for QA and the rest of the site, currently we use the folder structure to switch the call from one class to the other
if (AssetPath == "Websites QA")
{
InputHelperQA.Navigation();//Calling Navigation Section From Helper Class
}
else
{
InputHelper.Navigation();
}
But i feel it is a very tedious way of doing this task. Is there a better way of accomplishing this?, obviously just appending InputHelper + "QA" does not work but some thing along those lines where we only have to call the method once instead of having to wrap an if else around the call.
You really shouldn't have separate code for different environments, besides being branches representing your environments.
You really should store your configuration in a config file or database.
You could do worse than:
1) Have an interface (which you may already have, truth be told)
public interface IInputHelper
{
void Navigation();
}
2) Derive your two instances as you already have:
public class InputHelper : IInputHelper { }
public class InputHelperQA : IInputHelper { }
3) Create some kind of a dispatch manager:
public sealed class InputDispatch
{
private Dictionary<string, IInputHelper> dispatch_ = new Dictionary<string, IInputHelper>(StringComparer.OrdinalIgnoreCase);
public InputDispatch()
{
dispatch_["Websites QA"] = new InputDispatchQA();
dispatch_["Default"] = new InputDispatch();
}
public void Dispatch(string type)
{
Debug.Assert(dispatch_.ContainsKey(type));
dispatch_[type].Navigation();
}
}
I would use Dependency Injection. StructureMap (as just one example) will let you specify which concrete type to provide for an interface via a config file.
http://docs.structuremap.net/XmlConfiguration.htm
I chose to expose some new behavior using composition vs. injecting a new object into my consumers code OR making the consumer provide their own implementation of this new behavior. Did I make a bad design decision?
I had new requirements that said that I needed to implement some special behavior in only certain circumstances. I chose to define a new interface, implement the new interface in a concrete class that was solely responsible for carrying out the behavior. Finally, in the concrete class that the consumer has a reference to, I implemented the new interface and delegate down to the class that does the work.
Here are the assumptions that I was working with...
I haven an interface, named IFileManager that allows implementors to manage various types of files
I have a factory that returns a concrete implementation of IFileManager
I have 3 implementations of IFileManager, these are (LocalFileManager, DfsFileManager, CloudFileManager)
I have a new requirements that says that I need to manage permissions for only the files being managed by the CloudFileManager, so the behavior for managing permissions is unique to the CloudFileManager
Here is the test that led me to the code that I wrote...
[TestFixture]
public class UserFilesRepositoryTest
{
public interface ITestDouble : IFileManager, IAclManager { }
[Test]
public void CreateResume_AddsPermission()
{
factory.Stub(it => it.GetManager("cloudManager")).Return(testDouble);
repository.CreateResume();
testDouble.AssertWasCalled(it => it.AddPermission());
}
[SetUp]
public void Setup()
{
testDouble = MockRepository.GenerateStub<ITestDouble>();
factory = MockRepository.GenerateStub<IFileManagerFactory>();
repository = new UserFileRepository(factory);
}
private IFileManagerFactory factory;
private UserFileRepository repository;
private ITestDouble testDouble;
}
Here is the shell of my design (this is just the basic outline not the whole shibang)...
public class UserFileRepository
{
// this is the consumer of my code...
public void CreateResume()
{
var fileManager = factory.GetManager("cloudManager");
fileManager.AddFile();
// some would argue that I should inject a concrete implementation
// of IAclManager into the repository, I am not sure that I agree...
var permissionManager = fileManager as IAclManager;
if (permissionManager != null)
permissionManager.AddPermission();
else
throw new InvalidOperationException();
}
public UserFileRepository(IFileManagerFactory factory)
{
this.factory = factory;
}
private IFileManagerFactory factory;
}
public interface IFileManagerFactory
{
IFileManager GetManager(string managerName);
}
public class FileManagerFactory : IFileManagerFactory
{
public IFileManager GetManager(string managerName)
{
IFileManager fileManager = null;
switch (managerName) {
case "cloudManager":
fileManager = new CloudFileManager();
break;
// other managers would be created here...
}
return fileManager;
}
}
public interface IFileManager
{
void AddFile();
void DeleteFile();
}
public interface IAclManager
{
void AddPermission();
void RemovePermission();
}
/// <summary>
/// this class has "special" behavior
/// </summary>
public class CloudFileManager : IFileManager, IAclManager
{
public void AddFile() {
// implementation elided...
}
public void DeleteFile(){
// implementation elided...
}
public void AddPermission(){
// delegates to the real implementation
aclManager.AddPermission();
}
public void RemovePermission() {
// delegates to the real implementation
aclManager.RemovePermission();
}
public CloudFileManager(){
aclManager = new CloudAclManager();
}
private IAclManager aclManager;
}
public class LocalFileManager : IFileManager
{
public void AddFile() { }
public void DeleteFile() { }
}
public class DfsFileManager : IFileManager
{
public void AddFile() { }
public void DeleteFile() { }
}
/// <summary>
/// this class exists to manage permissions
/// for files in the cloud...
/// </summary>
public class CloudAclManager : IAclManager
{
public void AddPermission() {
// real implementation elided...
}
public void RemovePermission() {
// real implementation elided...
}
}
Your approach to add your new behavior only saved you an initialization in the grand scheme of things because you to implemented CloudAclManager as separate from CloudFileManager anyways. I disagree with some things with how this integrates with your existing design (which isn't bad)...
What's Wrong With This?
You separated your file managers and made use of IFileManager, but you didn't do the same with IAclManager. While you have a factory to create various file managers, you automatically made CloudAclManager the IAclManager of CloudFileManager. So then, what's the point of having IAclManager?
To make matters worse, you
initialize a new CloudAclManager
inside of CloudFileManager every time you try to get its ACL
manager - you just gave factory
responsibilities to your
CloudFileManager.
You have CloudFileManager implement IAclManager on top of having it as a property. You just moved the rule that permissions are unique to CloudFileManager into your model layer rather than your business rule layer. This also results in supporting the unnecessary
potential of circular referencing between self and property.
Even if you wanted
CloudFileManager to delegate the
permission functionality to
CloudAclManager, why mislead other
classes into thinking that
CloudFileManager handles its own
permission sets? You just made your
model class look like a facade.
Ok, So What Should I Do Instead?
First, you named your class CloudFileManager, and rightly so because its only responsibility is to manage files for a cloud. Now that permission sets must also be managed for a cloud, is it really right for a CloudFileManager to take on these new responsibilities? The answer is no.
This is not to say that you can't have code to manage files and code to manage permissions in the same class. However, it would then make more sense for the class to be named something more general like CloudFileSystemManager as its responsibilities would not be limited to just files or permissions.
Unfortunately, if you rename your class it would have a negative effect on those currently using your class. So how about still using composition, but not changing CloudFileManager?
My suggestion would be to do the following:
1. Keep your IAclManager and create IFileSystemManager
public interface IFileSystemManager {
public IAclManager AclManager { get; }
public IFileManager FileManager { get; }
}
or
public interface IFileSystemManager : IAclManager, IFileManager {
}
2. Create CloudFileSystemManager
public class CloudFileSystemManager : IFileSystemManager {
// implement IFileSystemManager
//
// How each manager is set is up to you (i.e IoC, DI, simple setters,
// constructor parameter, etc.).
//
// Either way you can just delegate to the actual IAclManager/IFileManager
// implementations.
}
Why?
This will allow you to use your new behavior with minimal impact to your current code base / functionality without affecting those who are using your original code. File management and permission management can also coincide (i.e. check permissions before attempting an actual file action). It's also extensible if you need any other permission set manager or any other type of managers for that matter.
EDIT - Including asker's clarification questions
If I create IFileSystemManager : IFileManager, IAclManager, would the repository still use the FileManagerFactory and return an instance of CloudFileSystemManager?
No, a FileManagerFactory should not return a FileSystemManager. Your shell would have to update to use the new interfaces/classes. Perhaps something like the following:
private IAclManagerFactory m_aclMgrFactory;
private IFileManagerFactory m_fileMgrFactory;
public UserFileRepository(IAclManagerFactory aclMgrFactory, IFileManagerFactory fileMgrFactory) {
this.m_aclMgrFactory = aclMgrFactory;
this.m_fileMgrFactory = fileMgrFactory;
}
public void CreateResume() {
// I understand that the determination of "cloudManager"
// is non-trivial, but that part doesn't change. For
// your example, say environment = "cloudManager"
var environment = GetEnvMgr( ... );
var fileManager = m_fileMgrFactory.GetManager(environment);
fileManager.AddFile();
// do permission stuff - see below
}
As for invoking permission stuff to be done, you have a couple options:
// can use another way of determining that a "cloud" environment
// requires permission stuff to be done
if(environment == "cloudManager") {
var permissionManager = m_aclMgrFactory.GetManager(environment);
permissionManager.AddPermission();
}
or
// assumes that if no factory exists for the environment that
// no permission stuff needs to be done
var permissionManager = m_aclMgrFactory.GetManager(environment);
if (permissionManager != null) {
permissionManager.AddPermission();
}
I think that composition is exactly the right means to to this kind of trick. But I think you should keep it more simple (KISS) and just make an IAclManager property in the IFileManager and set it to null by default and set the SecurityManager implementation for the cloud service there.
This has different upsides:
You can check if permissions need to be checked by nullchecking the securityManager property. This way, if there doesn't need to be permissionsManaging done (as with localfile system), you don't have exceptions popping up. Like this:
if (fileManager.permissionsManager != null)
fileManager.permissionsManager.addPermission();
When you then carry out the task (to add or delete a file), you can check again if there's a permissionsManager and if the permission is given, if not throw exception (as you'll want to throw the exception when a permission to do an action is missing, not if a permission is missing in general if you're not going to add or delete files).
You can later on implement more IAclManagers for the other IFileManagers when your customer changes the requirements next time the same way as you would now.
Oh, and then you won't have such a confusing hierarchy when somebody else looks at the code ;-)
In general it looks good, but I do have a few suggestions. It seems that your CreateResume() method implementation demands a IFileManager that is also an IAclManager (or else it throws an exception).
If that is the case, you may want to consider adding an overload to your GetManager() method in which you can specify the interface that you require, and the factory can have the code that throws an exception if it doesn't find the right file manager. To accompolish this you can add another interface that is empty but implements both IAclManager and IFileManager:
public interface IAclFileManager : IFileManager, IAclManager {}
And then add the following method to the factory:
public T GetManager<T>(string name){ /* implementation */}
GetManager will throw an exception if the manager with the name given doesn't implement T (you can also check if it derives from or is of type T also).
All that being said, if AddPermissions doesn't take any parameters (not sure if you just did this for the post), why not just call AddPermissions() from CloudFileManager.AddFile() method and have it completely encapsulated from the user (removing the need for the new IAclManager interface)?
In any event, doesn't seem like a good idea to call AddFile in the CreateResume() method and only then throw the exception (since you now you have now created a file without the correct permissions which could be a security issue and also the consumer got an exception so he may assume that AddFile didn't succeed, as opposed to AddPermission).
Good luck!