I have a class for my acquisition device. Then I want to create another class that generates random samples for when my acquisition device is not connected.
This is my object:
private object AmplifierObj;
And I want a create it like that
if (AmpSettingsObj.DaqDevice == "noAmp")
AmpObj = new NoAmpManager(sampleRate: sampleRate);
else
AmpObj = new USBampManager(optCalibrationFlag: calibrationFlag,
serialNumbers: serialNumbers, sampleRate: sampleRate);
However, when I call one of the methods I get the error "object" does not contain a definition for the method . Both classes have exactly the same methods implemented. What would be the best way of implementing it? Should I use a generic class as a placeholder?
If both classes have the same methods you should have an interface (IAmplifier) and both classes should implement this interface.
This can be easily done by right clicking one of the classes and selecting Refactor / Extract Interface.
Assuming your interface name is IAmplifier, have both classes implement the same interface such as:
public class NoAmpManager : IAmplifier
{
... (Methods)
... (Properties)
}
public class USBampManager : IAmplifier
{
... (Methods)
... (Properties)
}
Then, instead of
private object AmplifierObj;
Use
private IAmplifier AmplifierObj;
You can do it like this
public class AmplifierObj
{
public Object AnySameProperty { get; set; }
}
public class NoAmpManager: AmplifierObj
{
public void Foo()
{
}
}
public class USBampManager : AmplifierObj
{
public void Bar()
{
}
}
But always must call the sub class property you should check object type
AmplifierObj AmpObj;
if (AmpSettingsObj.DaqDevice == "noAmp")
AmpObj = new NoAmpManager(sampleRate: sampleRate);
else
AmpObj = new USBampManager(optCalibrationFlag: calibrationFlag,
serialNumbers: serialNumbers, sampleRate: sampleRate);
if (AmpObj.GetType() == typeof(NoAmpManager))
((NoAmpManager)AmpObj).Foo();
else
((USBampManager)AmpObj).Bar();
Related
I've made a class with T. It looks like this.
public interface ISendLogic<T> where T : NarcoticsResult
{
ChangeType Change_New();
ChangeType Change_Cancel();
PurchaseType Purchase_New();
PurchaseType Purchase_Cancel();
}
public class SendLogic<T> : ISendLogic<T> where T : NarcoticsResult
{
private eReportType _type;
private bool Send_Change()
{
// Send to server by xml file
}
private bool Send_Purchase()
{
// Send to server by xml file
}
public ChangeType Change_New()
{
_type = change_new;
Send_Change();
}
public ChangeType Change_Cancel()
{
_type = change_cancel;
Send_Change();
}
public PurchaseType Purchase_New()
{
_type = purchase_new;
Send_Purchase();
}
public PurchaseType Purchase_Cancel()
{
_type = purchase_cancel;
Send_Purchase();
}
}
There are two types, ChangeType and PurchaseType
and these are inherited from NarcoticsResult.
I thought the person who want to use this class would use it like this.
// this class can only be used when someone wants to use change function
var logic = SendLogic<ChangeType >();
logic.Change_New();
logic.Change_Cancel();
Here is a question.
I want to force this class to be used only as I thought.
I mean, I want to prevent it to be used like this.
var logic = SendLogic<ChangeType>();
logic.Change_New(); // OK
logic.Purchase_New(); // You should make this class like SendLogic<PurchaseType>()
I thought I add some code which check type of T in every function.
How do you think the way I thought. I think there are better way to fix it
Please tell me a better way
thank you.
Personally, I don't think you need a generic class in this case. What you need is either an abstract base class or an interface. I personally love the interface approach as below:
public interface ISendLogic {
void New();
void Cancel();
}
So now you've got a contract that will force the consumer of your code to use New or Cancel methods only.
The next step you can implement that send logic interface for your specific implementation:
public class ChangeSendLogic : ISendLogic {
private eReportType _type;
public ChangeSendLogic(
/*you can put the necessary parameters in the constructor
and keep it as private fields in the object*/
)
{
}
private bool Send_Change()
{
// Send to server by xml file
}
public void New()
{
_type = change_new;
Send_Change();
}
public void Cancel()
{
_type = change_cancel;
Send_Change();
}
}
public class PurchaseSendLogic : ISendLogic {
private eReportType _type;
public PurchaseSendLogic(
/*you can put the necessary parameters in the constructor
and keep it as private fields in the object*/
)
{
}
private bool Send_Purchase()
{
// Send to server by xml file
}
public void New()
{
_type = change_new;
Send_Purchase();
}
public void Cancel()
{
_type = change_cancel;
Send_Purchase();
}
}
From here you can see those two classes handle the implementation for each type nicely. You can think this is as an implementation of single responsibility principle. So if you have one more type, you can just add one more implementation of this interface rather than updating the existing classes.
If you want to hide the creation of those objects, in the next part you can introduce a kind of factory or selector as below:
public enum SendLogicType {
Change,
Purchase
}
public static SendLogicSelector {
public static ISendLogic GetSendLogic(SendLogicType type)
{
switch(type)
{
case SendLogicType.Change:
return new ChangeSendLogic();
case SendLogicType.Purchase:
return new PurchaseSendLogic();
}
}
}
This is how the code will be consumed:
ISendLogic sendLogic = SendLogicSelector.GetSendLogic(SendLogicType.Change);
sendLogic.New(); // change new logic executed
sendLogic.Cancel(); // change cancel logic executed
sendLogic = SendLogicSelector.GetSendLogic(SendLogicType.Purchase);
sendLogic.New(); // purchase new logic executed
sendLogic.Cancel(); // purchase cancel logic executed
Hopefully, you can get the idea of my approach. Good luck! :)
Thank you for your comment
I divided it into two parts like below
public class ChangeSendLogic : SendLogic<ChangeType>, IChangeLogic
public class PurchaseSendLogic : SendLogic<PurchaseType>, IPurchaseLogic
And I also divided interface too
public interface IChangeLogic
{
ChangeType Change_New();
ChangeType Change_Cancel();
}
public interface IPurchaseLogic
{
PurchaseType Purchase_New();
PurchaseType Purchase_Cancel();
}
And I made SendLogic<T> class to abstract class.
This is because I want to make the person who wants to use this class to use a class that inherits from this class without directly accessing it.
Thank you for your comment. I got a good idea.
I'd like to have two simple calls in a class that would be transformed by other classes. Something like:
ObjectCreator.CreateBlank<Human>();
ObjectCreator.CreatePopulated<Human>();
ObjectCreator.CreateBlank<Dog>();
ObjectCreator.CreatePopulated<Dog>();
I currently do this:
public class ObjectCreator
{
public static T CreateBlank<T>()
{
return Activator.CreateInstance<T>();
}
public static T CreatePopulated<T>()
{
//Somehow return new object with populated properties
}
}
I am struggling with the populated part. I'd like it to return a "default" object of that type with defined properties. I've tried a few things involving passing in interfaces, but it gets messy fast (I don't expect this to be particularly clean either)
So If I called ObjectCreator.CreatePopulated(), I'd like it to somehow go to a different class where I create a new Anything, and fill it's properties to specific values. It feels like I'm close but missing a piece of the puzzle here.
My end game here is to have the call be as simple / readable as possible.
Any help is appreciated.
I DO realize it'd probably be easier to simply call a class that creates and populates each object, but this is a learning exercise for me and I'd like to attempt to get this working as generically as possible.
I would recommend doing something like this:
public interface IPopulatable
{
void Populate();
}
public class ObjectCreator
{
public static T CreateBlank<T>() where T : new ()
{
return new T();
}
public static T CreatePopulated<T>() where T : IPopulatable, new()
{
var populatable = new T();
populatable.Populate();
return populatable;
}
}
public class Human : IPopulatable
{
public string Name { get; set; }
public void Populate()
{
Name = "Joe";
}
}
I'm trying to learn somethings about Dependency Injection and Specification Pattern.
If I have this scenario: I have three methods and they have different validation rules. This rules are validated by Specifications. So... My class must receive on the constructor these Specifications like this?
public PostService(IRepositorio rep, ISpecificationSave ss, SpecificationGet g, ISpecificationDelete sd) {
// do things...
}
But if is this correct, when I add a new method, I need to change de constructor to receive more one Specification?
Or, even using Dependency Inject, is better, in this case, create an instance of Specification on method how's use the Specification like that:
public void DoSomeThing(MyObject object) {
Specification<MyObject> specification = new Specification<MyObject>();
// do things...
}
I know the question is simple for some one of you, but I'm trying to learn those kinds of patterns yet.
You can use these Specifications in each validator by them adding one by one in your class, using Specitication Pattern, as follow:
public Class Class1 : IClass1 {
private List<ISpecification> contents;
private List<ISpecification> specializations;
public List GetContents() {
return contents;
}
public Set GetFeatures() {
return specifications;
}
public Class1() {
features = new List<ISpecification>(){//put specializations who belongs this class here};
specialications = new List<ISpecification>();
}
public boolean Validator1() {
foreach(ISpecification as spec in this.specializations) {
if (!spec.GetSpecification().IsSatisfiedBy(this))
return false;
}
return true;
}
}
public class Specification1 : ISpecification {
private object requiredFeature;
public Specification1(object feature) {
requiredFeature = feature;
}
public boolean IsSatisfiedBy(IClass class) {
return class.GetFeatures().contains(requiredFeature);
}
}
Then, you can add specifications in your application by:
IClass1 class = new Class1();
class.GetFeatures().add(new Specialization1(// some feature));
class.GetFeatures().add(new Specialization2(// some feature));
class.GetFeatures().add(new Specialization3(// some feature));
I have a group of classes (following strategy pattern) in my project. In the main function, I receive an enum value from the server and based on that I create an object of the base class type.
I am using switch/case statement to achieve this. I read somewhere that the Open/Closed principle does not allow opening a function to add a new case statement whenever a new class is added.
I am thinking of using a Activator.CreateInstance(). Is there any drawback to it.
Is there any other way to create an object from the enum type?
Adding example below even though it is not a full fledged Strategy pattern
abstract public class Mammal
{
public abstract void MakeSound()
}
class Cat:Mammal
{
public override void MakeSound()
{
Console.WriteLine("Meow");
}
}
class Dog:Mammal
{
public override void MakeSound()
{
Console.WriteLine("Bow");
}
}
Main()
{
MammalTypes mammalType = RecieveValueFromServer();
Mammal mammalBase
switch(mammalType) // need to make this dynamic depending upon Enum type
{
case MammalTypes.Cat:mammalBase = new Cat()
break;
case MammalTypes.Dog:mammalBase = new Dog()
break;
}
mammalBase.MakeSound()
}
One method for achieving true OCP might be the following:
Define an abstract method Is to force every concrete subtype of Mammal to specify whether it is appropriate for a given value of the enum:
abstract public class Mammal
{
public abstract void MakeSound();
public abstract bool Is(MammalTypes mammalType);
}
The implementations of Is in the subclasses would look like:
class Cat : Mammal
{
// other specific members
public override bool Is(MammalTypes mammalType)
{
return mammalType == MammalTypes.Cat;
}
}
class Dog : Mammal
{
// other specific members
public override bool Is(MammalTypes mammalType)
{
return mammalType == MammalTypes.Dog;
}
}
This being done, we can now create a MammalFactory class that, when given a Mammal enum value scans through the available classes and, when it finds a match, it returns an instance of that class:
public class MammalFactory
{
private readonly IEnumerable<Type> _mammalTypes;
public MammalFactory()
{
var currentAssembly = Assembly.GetExecutingAssembly();
_mammalTypes = currentAssembly.GetTypes()
.Where(t => typeof(Mammal).IsAssignableFrom(t) && !t.IsAbstract);
}
public Mammal Create(MammalTypes mammalType)
{
return _mammalTypes
.Select(type => CreateSpecific(type, mammalType))
.First(mammal => mammal != null);
}
public Mammal CreateSpecific(Type type, MammalTypes mammalEnumType)
{
var mammalInstance = (Mammal)Activator.CreateInstance(type);
return mammalInstance.Is(mammalEnumType) ? mammalInstance : null;
}
}
The final usage will look like this:
var mammalFactory = new MammalFactory();
var guessWhatMammal = mammalFactory.Create(MammalTypes.Cat);
This fully complies to OCP. It is only necessary to create a new Mammal class for it to be automatically wired and ready to use within the application. (no need to modify anything else in the application, except for the enum itself)
There are some problems with this approach:
it only scans the currently executing assembly for Mammal types
it has to create an instance of Mammal every time it needs to test whether that type is appropriate
While these issues can be addressed, one is still left: complexity.
This is complex because:
we've doubled the amount of code needed
the auto-wiring might be confusing for people new to the project
I think the conclusion is this: design patterns are not strict rules. It's not worth doing something just to conform to a given design.
Instead, we have to be pragmatic and find that perfect balance between pattern conformance and usefulness/simplicity/readability. This heavily depends on the problem we attempt to solve and in many cases it might very well be the switch statement you presented in the question.
You could use a Dictionary from the enum type to a function. The functions creates your strategy object:
public delegate Strategy StrategyFactory();
var strategyFactories = new Dictionary<MyEnum, StrategyFactory>();
This dictionary used to create your objects based on enum values:
var newStategy = strategyFactories[myEnumValue]();
the factory functions need to be added to the dictionary somehow. For that you can expose register (and maybe unregister) methods.
You could create an Attribute that takes the Type that the enum value represents and apply it to the enum field like so:
enum MyEnum {
[Creates(typeof(FooStrategy))]
Foo,
[Creates(typeof(BarStrategy))]
Bar,
// etc.
}
[AttributeUsage(AttributeTargets.Field, Inherited=false, AllowMultiple=false)]
sealed class CreatesAttribute : Attribute {
public Type TypeToCreate { get; private set; }
public CreatesAttribute(Type typeToCreate) {
TypeToCreate = typeToCreate;
}
public static IDictionary<T, Func<U>> GenerateLookup<T,U>() {
var query = from field in typeof(T).GetFields()
let creates = field.GetCustomAttriubtes(typeof(CreatesAttribute), false) as CreatesAttribute[]
let method = CreationMethod(typeof(U)) // create your type here
let key = (T)field.GetValue(null)
select new { Key = key, Method = method };
return q.ToDictionary(item => item.Key, item => item.Method);
}
}
The part left up to you is how you want to create an instance of your class. If they all have the same constructor, then this method will be easy as you can call Type.GetConstructor(Type[]) and then call Invoke your ConstructorInfo instance, or you could use an IoC container and resolve an instance from the type, not worrying so much about constructors with different parameters.
Then you can create a static class for extension methods on your enum:
public static class MyEnumExtensions {
static readonly IDictionary<MyEnumType, MyBaseStrategyType> lookup =
CreatesAttribute.GenerateLookup<MyEnumType, MyBaseStrategyType>();
public static MyBaseStrategyType CreateInstance(this MyEnumType key) {
return lookup[key](/* pass any common constructor values */);
}
}
Finally you would call it like so:
var myEnum = MyEnumType.Foo;
var strategy = myEnum.CreateInstance();
// use your strategy
This should keep you from violating the open/closed principle and allow you to add as many classes as you want and only change the Enum which can be made generic enough to create an instance of the strategy directly from the enum value.
What is the best way to implement polymorphic behavior in classes that I can't modify? I currently have some code like:
if(obj is ClassA) {
// ...
} else if(obj is ClassB) {
// ...
} else if ...
The obvious answer is to add a virtual method to the base class, but unfortunately the code is in a different assembly and I can't modify it. Is there a better way to handle this than the ugly and slow code above?
Hmmm... seems more suited to Adapter.
public interface ITheInterfaceYouNeed
{
void DoWhatYouWant();
}
public class MyA : ITheInterfaceYouNeed
{
protected ClassA _actualA;
public MyA( ClassA actualA )
{
_actualA = actualA;
}
public void DoWhatYouWant()
{
_actualA.DoWhatADoes();
}
}
public class MyB : ITheInterfaceYouNeed
{
protected ClassB _actualB;
public MyB( ClassB actualB )
{
_actualB = actualB;
}
public void DoWhatYouWant()
{
_actualB.DoWhatBDoes();
}
}
Seems like a lot of code, but it will make the client code a lot closer to what you want. Plus it'll give you a chance to think about what interface you're actually using.
Check out the Visitor pattern. This lets you come close to adding virtual methods to a class without changing the class. You need to use an extension method with a dynamic cast if the base class you're working with doesn't have a Visit method. Here's some sample code:
public class Main
{
public static void Example()
{
Base a = new GirlChild();
var v = new Visitor();
a.Visit(v);
}
}
static class Ext
{
public static void Visit(this object b, Visitor v)
{
((dynamic)v).Visit((dynamic)b);
}
}
public class Visitor
{
public void Visit(Base b)
{
throw new NotImplementedException();
}
public void Visit(BoyChild b)
{
Console.WriteLine("It's a boy!");
}
public void Visit(GirlChild g)
{
Console.WriteLine("It's a girl!");
}
}
//Below this line are the classes you don't have to change.
public class Base
{
}
public class BoyChild : Base
{
}
public class GirlChild : Base
{
}
I would say that the standard approach here is to wrap the class you want to "inherit" as a protected instance variable and then emulate all the non-private members (method/properties/events/etc.) of the wrapped class in your container class. You can then mark this class and its appropiate members as virtual so that you can use standard polymorphism features with it.
Here's an example of what I mean. ClosedClass is the class contained in the assembly whose code to which you have no access.
public virtual class WrapperClass : IClosedClassInterface1, IClosedClassInterface2
{
protected ClosedClass object;
public ClosedClass()
{
object = new ClosedClass();
}
public void Method1()
{
object.Method1();
}
public void Method2()
{
object.Method2();
}
}
If whatever assembly you are referencing were designed well, then all the types/members that you might ever want to access would be marked appropiately (abstract, virtual, sealed), but indeed this is unfortunately not the case (sometimes you can even experienced this issue with the Base Class Library). In my opinion, the wrapper class is the way to go here. It does have its benefits (even when the class from which you want to derive is inheritable), namely removing/changing the modifier of methods you don't want the user of your class to have access to. The ReadOnlyCollection<T> in the BCL is a pretty good example of this.
Take a look at the Decorator pattern. Noldorin actually explained it without giving the name of the pattern.
Decorator is the way of extending behavior without inheriting. The only thing I would change in Noldorin's code is the fact that the constructor should receive an instance of the object you are decorating.
Extension methods provide an easy way to add additional method signatures to existing classes. This requires the 3.5 framework.
Create a static utility class and add something like this:
public static void DoSomething(this ClassA obj, int param1, string param2)
{
//do something
}
Add a reference to the utility class on the page, and this method will appear as a member of ClassA. You can overload existing methods or create new ones this way.