我有以下代码可以在Base类的对象下执行操作:
class Program
{
static void Main(string[] args)
{
var list = new List<Base>() { new A(), new B() };
var v = new Visitor();
list.ForEach(e => e.Accept(v));
}
}
public abstract class Base
{
public abstract void Accept(Visitor visitor);
}
public class A : Base
{
public override void Accept(Visitor visitor) => visitor.Visit(this);
}
public class B : Base
{
public override void Accept(Visitor visitor) => visitor.Visit(this);
}
public class Visitor
{
Writer writer = new Writer();
public void Visit(A a) => writer.Write(a);
public void Visit(B b) => writer.Write(b);
}
public class Writer
{
public void Write(A a) => Console.WriteLine("A");
public void Write(B b) => Console.WriteLine("B");
}
我想将Writer
划分为单独的类,因为将会有许多其他具有复杂层次结构的实体。可能是:
public interface Writer<T> where T : Base
{
void Write(T t);
}
public class WriterA : Writer<A>
{
public void Write(A t) => Console.WriteLine("A");
}
public class WriterB : Writer<B>
{
public void Write(B t) => Console.WriteLine("B");
}
但是我不知道如何通过给定的type参数实例化适当的类,而不是显式调用它们。谢谢。
答案 0 :(得分:1)
您将需要写WriterFactory
:
class WriterFactory{
Dictionary<string, Func<object>> _creators = {
{ "A", ()=> new WriterA() },
{ "B", ()=> new WriterB() }
};
public Writer<T> Create<T>(){
return (Writer<T>)_creators[typeof(T).Name]();
}
比起您可以在Visitor
中使用它而言:
public class Visitor
{
Writer writerFactory = new WriterFactory();
public void Visit(A a) => writerFactory.Create<A>().Write(a);
public void Visit(B b) => writerFactory.Create<B>().Write(b);
}