你能告诉我它是工厂,战略还是MVC设计模式?
public interface MainObject<T>
{
void add();
T get();
}
class Person1 : MainObject<Person1>
{
public Person1(int id, string name)
{
// define
}
public void add()
{
// add
}
public Person1 get()
{
// return
}
}
class Person2 : MainObject<Person2>
{
public Person2(int id, string name, bool status)
{
// define
}
public void add()
{
// add
}
public Person2 get()
{
// return
}
}
class Client
{
public User()
{
}
public void add<T>(T obj) where T : Object<T>
{
obj.add();
}
public T get<T>(T obj) where T : Object<T>
{
return obj.get();
}
}
static class Program
{
static void Main()
{
Client client = new Client();
client.add( new Person1(123,"Duke") );
client.add( new Person2(456,"Dave",true) );
Person1 foundPerson1 = client.get( new Person1(123,null) ); // (123,"Duke")
Person2 finedPerson2 = client.get( new Person1(null,"Dave",null) ); // (456,"Dave",true)
}
}
我用工厂和策略模式编写了我的代码,但我在这里看到了MVC MVC pattern differences的实现,它就像我的代码一样。现在我混淆了我的代码是什么模式。
答案 0 :(得分:0)
策略模式是一种提供不同行为的方式,而实现不会涉及调用代码。例如:
interface IPersonRepository{
IPerson GetPerson();
}
class PersonRepository : IPersonRepository{
public IPerson GetPerson(){
return GetDataFromDatabase();
}
private IPerson GetDataFromDatabase(){
// Get data straight from database.
}
}
class PersonRespositoryWithCaching : IPersonRepository{
public IPerson GetPerson(){
IPerson person = GetDataFromCache();
// Is person in cache?
if(person!=null){
// Person found in cache.
return person;
}else{
// Person not found in cache.
person = GetDataFromDatabase();
StoreDataInCache(person);
return person;
}
}
private IPerson GetDataFromCache(){
// Get data from cache.
}
private IPerson GetDataFromDatabase(){
// Get data straight from database.
}
}
class Program{
static void Main(){
IPersonRepository repository = null;
if(cachingEnabled){
repository = new PersonRepositoryWithCache();
}else{
repository = new PersonRepository();
}
// At this point the program doesn't care about the type of
// repository or how the person is retrieved.
IPerson person = repository.GetPerson();
}
}
工厂模式与结构中的策略模式类似,但不是实现工厂创建不同对象的不同通用行为。例如:
interface IPerson{}
class SomePerson : IPerson{}
class OtherPerson : IPerson{}
interface IPersonFactory{
void IPerson Create();
}
class SomePersonFactory : IPersonFactory{
public void IPerson Create(){ return new SomePerson(); }
}
class OtherPersonFactory : IPersonFactory{
public void IPerson Create(){ return new OtherPerson(); }
}
MVC模式是一种确保向用户显示数据的代码不与代码混合以检索或操纵应用程序的方法。模型将数据保存在内存中,View将其显示给用户,Controller允许用户与数据和应用程序进行交互。
可选模式(如Repository和Service)将与外部数据源交互的代码分开,或执行任何业务逻辑。
MVC模式的优点是您可以交换各种组件的实现来执行诸如从数据库或Web服务检索数据,或将数据显示为表或图形。同样,这与战略模式类似。
您的代码包含模型和存储库的元素。但是(以及缺少其他组件)代码混合在一起,因此它不是真正的MVC。