I am trying to implement the state design pattern using C++/CLI. This pattern requires that the State class be a friend of the Context. But C++/CLI does not allow a friend class. I understand that this is also the case with C#. Has anyone implemented the state pattern with C++/CLI or C#? I would like to know how you got around the absence of friend class.
Its done using Association (or what all the cool kids are calling Dependency Injection). Inject the state into the context. See the implementation on DoFactory
Having the State class be a friend of the Context class is not a requirement for implementing the State pattern. Wikipedia has an implementation without using the friend modifier.
You could keep state in a subclass, then replace sub class object with a different inheriting type when state changes.
class YourClass
{
private MyEnum _myStateEnum; // Wrap this with a public property
private MyInnerClass _myStateLogic; // Change this with appropriate type when above changes
public void AnExampleMethod()
{
_myStateLogic.AnExampleMethod();
}
internal abstract class MyInnerClass
{
public virtual abstract void AnExampleMethod();
}
internal class MyOtherInnerClass1: MyInnerClass
{
public override void AnExampleMethod() { }
}
internal class MyOtherInnerClass2: MyInnerClass
{
public override void AnExampleMethod() { }
}
}
Related
I'm a C++ developer learning C#, and I'm in a situation where I need a class C to have two members that belong to it that represent "robots." The robots need to be able to access private members of C, and they don't need to be used anywhere else. In C++ I'd use the "friend" keyword, but I don't know what to do here. I thought about doing something like this:
class C
{
private Member mem;
private Robot bot;
private class Robot
{
C owner;
public void function() { //Robot needs to use owner.mem here,
//but can't because it's private}
};
}
The trouble is that I don't know how to say that a Robot is "owned" by an instance of C, and can access its members.
One way to do it is to pass the outer class's instance to the inner class's constructor as a reference.
class C
{
private Member mem;
private Robot bot;
private class Robot
{
C owner;
public Robot(C c) {owner = c;}
public void function()
{
// Robot can use owner.mem here
}
};
}
There's no direct equivalent of friend - the closest that's available (and it isn't very close) is InternalsVisibleToAttribute but it breaks the relationships between classes and undermines some fundamental attributes of an OO language.
The only decent solution that has occurred to me is to invent an interface, ICClass, which only exposes the public methods, and have the Factory return ICClass interfaces.
This involves a fair amount of tedium - exposing all the naturally public properties again in the interface.
There are heaps of threads about this: Why does C# not provide the C++ style 'friend' keyword?
"Robot needs to use owner.mem here, but can't because it's private"
I think you want Protected with an inheritance model:
class C
{
protected Member mem;
protected Robot bot;
}
private class Robot : C
{
public void function() {
base.mem... // here you can use the base classes mem and bot
};
}
I wonder since there is no way how to implement a generic Decorator class in C# (is it?) like this:
public class Decorator<TDecoratorIterface> : TDecoratorInterface
{
public TDecoratorInterface Component {get; private set;}
protected Decorator(TDecoratorInterface component)
{
Component = component;
}
}
use like this:
public interface IDogDecorator
{
void Bark();
}
public class Dog : IDogDecorator
{
public void Bark()
{
Console.Write("I am a dog");
}
}
public class StinkingDog : Decorator<IDogDecorator>
{
public StinkingDog(IDogDecorator dog):base(dog)
{
}
public void Bark()
{
Component.Bark();
Console.WriteLine(" and I stink");
}
}
can such a thing be managed via PostSharp or any other AOP framework for .NET?
thank fro your answers, I spent half a day trying to create such a construct without any success, so any help is appreciatted:)
There's no direct equivalent to this construct, as C# doesn't allow the base class of a type to be dynamic. Remember that the generic type must be fully defined at compile time, not at usage time.
There's multiple possible ways to go: In the example above, the StinkingDog should just implement the IDogDecorator interface. So just specify that there. You're forwarding calls anyway.
public class StinkingDog : Decorator<IDogDecorator>, IDogDecorator
There would probably be frameworks that do what you want exactly (i.e. Rhino.Mocks is actually creating Mocks this way), but for production code, I'd really suggest not doing any AOP approach. It's clumsy and slow.
I have many classes in a project that need to all have a base set of the same constructors and 1 public method. Below is an example of this partial class:
public partial class SHIPMENT_LINE
{
private OracleConnection _rp = null;
private EntityConnection _rpe = null;
private static string _schema = "";
public SHIPMENT_LINE() { }
public SHIPMENT_LINE(BHLibrary.Configuration.ConnectionOption Environment)
{
SetConnection(Environment);
}
public void SetConnection(BHLibrary.Configuration.ConnectionOption Environment)
{
this._rp = Configuration.RPConnection(Environment);
this._rpe = Configuration.RPEntityConnection(Environment, out _schema);
}
}
I need to implement the same private variables, constructors, and the SetConnection method on each of my classes that I create. After this all exists in each class, then each class will do something different, so the classes are not all necessarily related, aside from the fact that they all have this same "Beginning."
How should I go about building each of these classes so that I do not have to implement this SetConnection method in each of the classes that I create?
Keep this in mind:
Due to other restrictions, I cannot inherit from another class in any of these classes. I can, however, use Interfaces if necessary.
I would suggest going for composition rather than inheritance...
Make each of the class implement an interface, then have another class (not related to these) which also implements the interface and has a concrete implementation of it. All the classes you've mentioned above should have an instance of this additional class and just call through to it.
Example
public partial class SHIPMENT_LINE : ISetConnection
{
private ConnectionSetter connector = new ConnectionSetter();
public void SetConnection(BHLibrary.Configuration.ConnectionOption Environment)
{
this.connector.SetConnection(Environment);
}
}
public class ConnectionSetter : ISetConnection
{
public void SetConnection(BHLibrary.Configuration.ConnectionOption Environment)
{
// Implementation
}
}
If you can't subclass then an abstract class is not a viable solution and interfaces are only going to give you the contract that your common classes conform to without any implementation.
I would suggest implementing the common functionality in a common class and using this as a private member in your other classes (I.E. composition rather than inheritance). Your other classes could all implement an interface to ensure they all have the same methods and they could just forward their calls onto the private classes implementation of the method.
E.G.
private MYClassWithCommonFunctionality xyz = new MYClassWithCommonFunctionality();
And then...
Private void MyCommonInterfaceMethod(object param)
{
// Do derived class specific stuff here...
xyz.MyCommonInterfaceMethod(param);
}
And as an added bonus and a bit of forward thinking....have the common class also share the same interface and pass an implementation of this into your other classes constructor. That way in the future you can swap the implementation for another.
If you cannot create a base class that will implement your common functionality (any reason why?) than you probably can use T4 template to generate partial class with your common methods.
Given the following:
public abstract class Base
{
// other stuff
public static void StaticMethod()
{
PrivateMethod();
}
// here should be PrivateMethod() declaration somehow
}
public sealed class Derived: Base
{
// other stuff
public void InstanceMethod()
{
// call somehow PrivateMethod
PrivateMethod();
}
}
I need to make use of PrivateMethod() from 2 different contexts (different assemblies). Once calling Base.StaticMethod(), and the second time by using an instance of the Derived class d.InstanceMethod();.
I am looking for a way how to design PrivateMethod() inside the Base class. Of course PrivateMethod() should not be visible outside the Base and Derived classes.
I was thinking something about "protected static PrivateMethod() {}" but I read I should not do that...
What do you recommend guys?
protected static void PrivateMethod() {}
Is OK (apart form the name) and does what you require. You won't need base. when calling it from Derived.
I had never heard this before, so I went looking for something that said what you described. I found this article: New Design Guideline: Avoid Protected Static. However, it only talks about protected static field.
I don't think the article actually makes a good case for what it is trying to say. Rather than just describing how protected statics can lead to complications, it uses a very simple example of the base class designer not setting the right access flags for something that should not be accessed by everyone.
That being said, there is still a point that protected static can lead to complications. Protected static means that any subclass can call a method at any time. This can lead to thread safety concerns if the method is written naively. It seems like the article was written in a way that it conveys "Don't do it" rather than "If you need to do it, be careful."
You could just call the public StaticMethod() from your derived class's InstanceMethod() ... since it indirects back to PrivateMethod() anyway. That way you can leave PrivateMethod() private. The implementation would be something like:
public abstract class Base
{
// other stuff
public static void StaticMethod()
{
PrivateMethod();
}
// here should be PrivateMethod() declaration somehow
private static void PrivateMethod()
{
// do stuff
}
}
public sealed class Derived: Base
{
// other stuff
public void InstanceMethod()
{
// call somehow PrivateMethod
StaticMethod();
}
}
PS: If there is need during StaticMethod to differentiate between a public caller or a derived class caller (from InstanceMethod) it could be either passed as parameter, or determined via reflection.
In C# you can have nested classes like this, which are useful if you have classes which do not have meaning outside the scope of one particular class, e.g. in a factory pattern:
public abstract class BankAccount
{
private BankAccount() {}
private sealed class SavingsAccount : BankAccount { ... }
private sealed class CheckingAccount : BankAccount { ... }
public BankAccount MakeSavingAccount() { ... }
public BankAccount MakeCheckingAccount() { ... }
}
Is this possible in PHP?
I've read that it was planned for PHP 5, then cancelled, then planned again, but can't find definitive info.
Does anyone know how to create nested classes (classes within the scope of another class) as in the above C# example using PHP 5.3?
No, this isn't possible in PHP. Classes must inhabit the global namespace; the best you can do is just pretend they don't exist in all of your other code.
This kind of thing is common in PHP; for example, PHP lacks static initializers, so if you want to eagerly initialize the static members of a class, it must be done by calling a public method from outside the class. Ugly.