I am getting runtime error Duck.quackableDuck and Duck.flyableDuck is inaccessible.
I have created two interfaces FlyableDuck and QuackableDuck. Class MallardDuck is inherited from class Duck.
using System;
//creating interfaces
public interface FlyableDuck
{
void fly();
}
public interface QuackableDuck
{
void quack();
}
//creating behavior classes
public class FlyWithWings:FlyableDuck
{
public void fly()
{
Console.WriteLine("I am flying.");
}
}
public class FlyNoWings: FlyableDuck
{
public void fly()
{
Console.WriteLine("I can't fly. :(");
}
}
public class Quacking: QuackableDuck
{
public void quack()
{
Console.WriteLine("Quack Quack!!");
}
}
public class NoQuack : QuackableDuck
{
public void quack()
{
Console.WriteLine("Can't quack :(");
}
}
public class SqueakQuack : QuackableDuck
{
public void quack()
{
Console.WriteLine("Squeak quack!!");
}
}
//creating abstrack class
public abstract class Duck
{
QuackableDuck quackableDuck;
FlyableDuck flyableDuck;
public Duck() { }
public abstract void display();
public void perfomFly()
{
flyableDuck.fly();
}
public void perfomQuack()
{
quackableDuck.quack();
}
public void swim()
{
Console.WriteLine("All ducks swim :)");
}
}
//subclass
public class MallardDuck:Duck
{
public MallardDuck()
{
quackableDuck = new Quacking();
flyableDuck = new FlyWithWings();
}
public override void display()
{
Console.WriteLine("I am Mallard Duck.");
}
}
public class Class2
{
public static void Main(String[] args)
{
MallardDuck mallard = new MallardDuck();
mallard.perfomFly();
mallard.perfomQuack();
Console.ReadKey();
}
}
These 2:
QuackableDuck quackableDuck;
FlyableDuck flyableDuck;
Are private (by default) so change it to:
public QuackableDuck quackableDuck;
public FlyableDuck flyableDuck;
You can also use protected/internal instead of public
Related
How to use dependency injection for generic interfaces? I want the IDrawView interface to be created in DrawPresenter, and it controls the view.
I do not know what to use, Ninject or something else. I am using WinForms.
Which is better to choose?
class Program
{
static void Main(string[] args)
{
IDrawPresenter prisenter = new DrawPresenter(new DrawWindow());
prisenter.Show();
Console.ReadLine();
}
}
public interface IView
{
void Show();
}
public interface IDrawView : IView
{
object GetGridDraw { get; }
}
public interface IPrisenter<TView> where TView : IView
{
void Show();
}
public interface IDrawPresenter : IPrisenter<IDrawView>
{
object SelectedDraws { get; }
}
public class DrawWindow : IDrawView
{
public object GetGridDraw => 1;
public void Show()
{
Console.WriteLine("Show Window");
}
}
public abstract class BasePresenter<TView> : IPrisenter<TView>
where TView : IView
{
protected BasePresenter(TView view)
{
View = view;
}
protected TView View { get; private set; }
public void Show()
{
View.Show();
}
}
public class DrawPresenter : BasePresenter<IDrawView>, IDrawPresenter
{
public DrawPresenter(IDrawView view): base(view)
{
}
public object SelectedDraws => View.GetGridDraw;
}
Can DI implement this?
IDrawPresenter prisenter = new DrawPresenter();
public DrawPresenter()
{
}
What I need to do for Presenter to manage the form.
Here is what I want to get. But this does not work ...
public class NinjectProgram
{
//Gets the inject kernal for the program.
public static IKernel Kernel { get; protected set; }
}
public class DependencyModule : NinjectModule
{
public override void Load()
{
Bind<IDrawView>().To<DrawWindow>();
}
}
static void Main(string[] args)
{
StandardKernel Kernel = new StandardKernel();
Kernel.Load(new DependencyModule());
IDrawPresenter prisenter = new DrawPresenter();
prisenter.Show();
Console.ReadLine();
}
public abstract class BasePresenter<TView> : IPrisenter<TView>
where TView : IView
{
protected BasePresenter()
{
View = NinjectProgram.Kernel.Get<TView>();
}
protected TView View { get; private set; }
public void Show()
{
View.Show();
}
}
Thank you all, that’s what I wanted to do. Perhaps this will help someone in the future.
static void Main(string[] args)
{
CompositionRoot.Wire(new DependencyModule());
IDrawPresenter prisenter = new DrawPresenter();//kernel.Get<IDrawPresenter>();
prisenter.Show();
Console.ReadLine();
}
public class CompositionRoot
{
private static IKernel _ninjectKernel;
public static void Wire(INinjectModule module)
{
_ninjectKernel = new StandardKernel(module);
}
public static T Resolve<T>()
{
return _ninjectKernel.Get<T>();
}
}
public class DependencyModule : NinjectModule
{
public override void Load()
{
Bind<IDrawView>().To<DrawWindow>();
}
}
public abstract class BasePresenter<TView> : IPrisenter<TView>
where TView : IView
{
protected BasePresenter()
{
View = CompositionRoot.Resolve<TView>();//NinjectProgram.Kernel.Get<TView>();
}
protected TView View { get; private set; }
}
Also include the presenter in the container and resolve it.
public class DependencyModule : NinjectModule {
public override void Load() {
Bind<IDrawView>().To<DrawWindow>();
Bind<IDrawPresenter>().To<DrawPresenter>();
}
}
All its dependencies, if registered, will also be resolved and injected into the presenter
static void Main(string[] args) {
var kernel = new StandardKernel();
kernel.Load(new DependencyModule());
IDrawPresenter presenter= kernel.Get<IDrawPresenter>();
presenter.Show();
Console.ReadLine();
}
The above is based on
public abstract class BasePresenter<TView> : IPrisenter<TView> where TView : IView {
protected BasePresenter(TView view) {
View = view;
}
protected TView View { get; private set; }
public void Show() {
View.Show();
}
}
public class DrawPresenter : BasePresenter<IDrawView>, IDrawPresenter {
public DrawPresenter(IDrawView view): base(view) {
}
public object SelectedDraws => View.GetGridDraw;
}
I have a Base class which is generic.
I have a concrete class which implements the base class.
How would I create a factory class/method for delivering different types of concrete classes?
Here an example:
public class ReceiverBase<T>
where T : IInterpreter
{ ... }
public class SpecialReceiver : ReceiverBase<OwnInterpreter> { ... }
public class ReceiverFactory<T>
where T : ReceiverBase<IInterpreter>, new()
public T Create(string type) {
switch(type) {
default:
return new SpecialReceiver();
}
}
}
The problem is that ReceiverBase seems not to be possible because the compiler only wants classes as Constraints, not interfaces.
And the second problem is that I cannot convert SpecialReceiver to T.
So is there a way to get this working?
=== EDIT: Added example according to first answer ===
public interface IInterpreter
{
}
public class OwnInterpreter : IInterpreter
{
public void Dispose()
{
throw new NotImplementedException();
}
public void DoSomething() { }
}
public abstract class ReceiverBase<T>
where T : IInterpreter
{
public T MyReceiver { get; set; }
internal abstract void Start();
}
public class SpecialReceiver<T> : ReceiverBase<T>
where T : IInterpreter, new()
{
public void CheckSomething()
{
MyReceiver.DoSomething();
}
internal override void Start()
{
MyReceiver = new T();
}
}
public class ReceiverFactory<T>
where T : IInterpreter, new()
{
public static ReceiverBase<T> Create(string type)
{
switch (type)
{
default:
return new SpecialReceiver<T>();
}
}
}
The Problem is: MyReceiver.DoSomething(); will not work.
Additionally I would have to call the factory like this: ReceiverFactory<OwnInterpreter>.Create(""); I'd like to have it that way: ReceiverFactory.Create("SpecialReceiver");
You can use generic method in your factory:
class Program
{
static void Main(string[] args)
{
var own = ReceiverFactory.Create<OwnInterpreter>();
var other = ReceiverFactory.Create<OtherInterpreter>();
own.Start();
other.Start();
Console.ReadLine();
}
}
interface IInterpreter
{
void DoSomething();
}
class OwnInterpreter : IInterpreter
{
public void DoSomething() { Console.WriteLine("Own"); }
}
class OtherInterpreter : IInterpreter
{
public void DoSomething() { Console.WriteLine("Other"); }
}
abstract class ReceiverBase<T> where T: IInterpreter, new()
{
public T Interpreter { get; set; }
public ReceiverBase()
{
Interpreter = new T();
}
public void Start()
{
Interpreter.DoSomething();
}
}
class SpecialReceiver : ReceiverBase<OwnInterpreter> { }
class OtherReceiver : ReceiverBase<OtherInterpreter> { }
static class ReceiverFactory
{
private static Dictionary<string, object> factories = new Dictionary<string, object>();
static ReceiverFactory()
{
RegisterFactory(() => new SpecialReceiver());
RegisterFactory(() => new OtherReceiver());
}
public static void RegisterFactory<T>(Func<ReceiverBase<T>> factory) where T : IInterpreter, new()
{
factories.Add(typeof(T).FullName, factory);
}
public static ReceiverBase<T> Create<T>() where T : IInterpreter, new()
{
var type = typeof(T);
return ((Func<ReceiverBase<T>>)factories[type.FullName]).Invoke();
}
}
In fact, you do not need "new()" constraint here, since you use factories.
I suggest you to change your code to:
public class ReceiverBase<T> where T : IInterpreter
{
}
public interface IInterpreter
{
}
public class SpecialReceiver<T> : ReceiverBase<T>
where T : IInterpreter
{
}
public class OwnInterpreter : IInterpreter
{
}
public class ReceiverFactory<T> where T : IInterpreter, new()
{
public ReceiverBase<T> Create(string type)
{
switch (type)
{
default:
return new SpecialReceiver<T>();
}
}
}
The reason why you cannot just return T in your case is, that there is no implicit conversion between SpecialReceiver and ReceiverBase<IInterpreter>.
I was able to find a solution which suits my needs.
I've added another interface IReciver which defines the properties and members I really need. The factory method returns IReceiver so I can omit all binding issues whith generics. Sometimes it is just that easy. :)
public interface IInterpreter { }
public interface IReceiver
{
bool Enabled { get; set; }
}
public class OwnInterpreter : IInterpreter
{
public void DoSomething() { }
}
public abstract class ReceiverBase<T> : IReceiver
where T : IInterpreter, new()
{
public T MyReceiver { get; set; }
internal abstract void Start();
private bool _isEnabled;
public bool Enabled { get { return _isEnabled; } set { _isEnabled = value; OnEnable(value); } }
internal abstract void OnEnable(bool isEnabled);
protected ReceiverBase()
{
MyReceiver = new T();
}
}
public class SpecialReceiver : ReceiverBase<OwnInterpreter>
{
public void CheckSomething()
{
MyReceiver.DoSomething();
}
internal override void Start()
{
// just for testing puropses
MyReceiver = new OwnInterpreter();
}
internal override void OnEnable(bool isEnabled)
{
MyReceiver = isEnabled ? new OwnInterpreter() : null;
}
}
public class ReceiverFactory
{
public static IReceiver Create(string type)
{
switch (type)
{
default:
return new SpecialReceiver();
}
}
}
public class Program
{
[STAThread]
public static void Main()
{
ReceiverFactory.Create("");
}
}
I am creating one console application. I have one class in which I wrote some methods. Now I want to override some methods of that class in a different class. But this should be override only if condition satisfied.
For example,
public partial Class MainClass
{
public string GetPath()
{
string temp = Method1();
return temp;
}
protected virtual string Method1()
{
//logic
}
}
If some condition satisfied then only overridden method should be called
public partial class ChildClass : MainCLass
{
public override void Method1()
{
//MY Logic
}
}
How can I achieve this? Is it possible to do so?
In ChildClass you can do something like this:
public partial class ChildClass : MainCLass
{
public override void Method1()
{
if(condition)
{
base.Method1();
return;
}
//YOUR LOGIC
}
}
EXAMPLE
public class A
{
public virtual void MethodA()
{
Console.WriteLine("A:MethodA");
}
}
public class B : A
{
public bool CallBase { get; set; }
public B()
{
CallBase = false;
}
public override void MethodA()
{
if (CallBase)
{
base.MethodA();
return;;
}
Console.WriteLine("B:MethodA");
}
}
class Program
{
static void Main(string[] args)
{
A a = new A();
B b = new B();
a.MethodA();
b.MethodA();
b.CallBase = true;
b.MethodA();
A c = new B();
c.MethodA();
A d = new B(true);
d.MethodA();
Console.ReadKey();
}
}
Output
A:MethodA
B:MethodA
A:MethodA
B:MethodA
A:MethodA
I'm trying to use the factory pattern and have created three interfaces.
ITest1
public interface ITest1: ITestX
{
void Write(string name);
}
ITest2
public interface ITest2: ITestX
{
void Read(string name);
}
and ITestX
public interface ITestX
{
}
The interfaces ITest1 and ITest1 are implemented in classes A and B:
public class A: ITest1
{
public void Write(string name)
{
Console.WriteLine(name);
}
}
public class B: ITest2
{
public void Read(string name)
{
Console.WriteLine(name);
}
}
As for the factory, my interface looks like this:
public interface IFactory
{
ITestX GetClass(ClassType cType);
ITestX GetClass(int cType);
}
The class ClassType:
public class ClassT
{
public int Type { get; set; }
public static class ClassType
{
public const int AType = 0;
public const int BType = 1;
}
}
The Factory class which implements the factory interface:
public class Factory : IFactory
{
public ITestX GetClass(ClassType cType)
{
return GetNetwork(networkType.Type);
}
public ITestX GetClass(int cType)
{
switch (cType)
{
case ClassT.ClassType.AType:
return new A();
case ClassT.ClassType.BType:
return new B();
default:
throw new NotImplementedException();
}
}
}
In my test method, I try to use the factory:
Factory factory = new Factory();
var typeClass = factory.GetClass(new ClassT{ Type = ClassT.ClassType.AType });
However, I can't use the Read or Write methods because they are not visible in typeClass. What's going on? Why can't I access them?
Because Factory.GetClass returns ITextX, and this interface doesn't have that methods declared.
You can try casting that objects to the interface you need and then you will have an opportunity to invoke corresponding methods.
UPDATE:
You can see an example implementation on the wiki page.
Example:
public interface ICanRead
{
string Read();
}
public interface ICanWrite
{
void Write(string name);
}
public interface ICanReadAndWrite : ICanRead, ICanWrite {}
class ConsoleReadWriter : ICanReadAndWrite
{
public string Read()
{
return Console.ReadLine();
}
public void Write(string name)
{
Console.WriteLine(name);
}
}
public interface IReadWriterFactory
{
ICanReadAndWrite GetClass();
}
public class ConsoleReadWriterFactory : IReadWriterFactory
{
public ICanReadAndWrite GetClass()
{
return new ConsoleReadWriter();
}
}
Create a class implementing the IReadWriterFactory interface for other Classes of ReadWriters.
I think what you rather need is this:
class Program
{
static void Main(string[] args)
{
ReadWriter myReadWriter = new ReadWriter(new ConsoleReaderWriterFactory());
string test = myReadWriter.Read();
myReadWriter.Write("this is abstract factory power");
}
}
public class ConsoleWriter : ICanWrite
{
public void Write(string name)
{
Console.WriteLine(name);
}
}
public class ConsoleReader : ICanRead
{
public string Read()
{
return Console.ReadLine();
}
}
public interface ICanWrite
{
void Write(string name);
}
public interface ICanReadAndWrite : ICanRead, ICanWrite { }
public interface ICanRead
{
string Read();
}
public class ReadWriter : ICanReadAndWrite
{
private ICanRead reader;
private ICanWrite writer;
public string Read()
{
return reader.Read();
}
public void Write(string name)
{
writer.Write(name);
}
public ReadWriter(IReaderWriterFactory factory)
{
reader = factory.CreateReader();
writer = factory.CreateWriter();
}
}
public interface IReaderWriterFactory
{
ICanRead CreateReader();
ICanWrite CreateWriter();
}
public class ConsoleReaderWriterFactory : IReaderWriterFactory
{
public ICanRead CreateReader()
{
return new ConsoleReader();
}
public ICanWrite CreateWriter()
{
return new ConsoleWriter();
}
}
I have a requirement of dynamically invoke a class and use the methods of that class.
public class A
{
public void test()
{
}
}
public Class B
{
public void test()
{
}
}
class object intermediate
{
//here will decide which class to be invoked
//return the invoked class instance
}
class clientclass
{
intermedidate client=new intermediate();
}
So can i access the methods of the invoked class, in the instance client.
Im using Framework 3.5. If child class inherited from the intermediate class, is it possible to achieve this? I dont want reflection here.
You can do like follows (not verified)
interface I
{
}
class A :I
{
}
Class B:I
{
}
class intermediate
{
public I GetInstance(int i)
{
if(i==1)
return new A();
else
return new B();
}
}
class clientclass
{
I client=new intermediate().GetInstance(1);
}
Try this
public interface IClassA
{
void Method();
}
public class ClassA : IClassA
{
public void Method()
{
}
}
public static class ObjectInjector
{
public static T GetObject<T>()
{
object objReturn = null;
if(typeof(T) == typeof(IClassA))
{
objReturn = new ClassA();
}
return (T)objReturn;
}
}
public class ClientClass
{
static void Main(string[] args)
{
IClassA objA = ObjectInjector.GetObject<IClassA>();
objA.Method();
}
}
You could try and do the interface implementation as the Șhȇkhaṝ has above.
You could also use an abstract class if you require initial processing before class A or B's test method is invoked.
Here is an example of a console app that demonstrates this:
public abstract class MainClass
{
public virtual void test()
{
Console.WriteLine("This is the abstract class");
}
}
public class A : MainClass
{
public override void test()
{
base.test();
Console.WriteLine("Class A");
}
}
public class B : MainClass
{
public override void test()
{
base.test();
Console.WriteLine("Class B");
}
}
public class Intermediate
{
public MainClass CreateInstance(string name)
{
if (name.ToUpper() == "A")
{
return new A();
}
else
{
return new B();
};
}
}
class Program
{
static void Main(string[] args)
{
Intermediate intermediate = new Intermediate();
var client = intermediate.CreateInstance("B");
client.test();
Console.ReadLine();
}
}