如果有人已经问过这个问题,我很抱歉,但是我没有找到关于这个特定场景的问题:
我有一个有状态和类型的实体。对于每种状态和每种类型,我应该向用户显示一个不同的页面,这个页面需要创建某种复杂的内容,因此它是用构建器模式创建的。但是,在某些情况下,这些页面可能是相同的。在某种情况下,我不需要检查类型。
可能出现的一些例子:
我考虑实现一个工厂(每个状态都有一个开关大小写),它将创建并返回抽象工厂的结果(每种类型都有一个工厂)。但是,我需要一些抽象类来解决这些工厂之间的“同一页”问题。
我真的需要这个复杂的结构吗?
发布于 2017-11-01 08:01:51
要根据“类型”的不同状态显示页面。因此,您的内部页面调用将根据您的上下文进行更改。因此,我建议您使用策略设计模式来实现此行为。
根据我对问题陈述的理解,下面是C#中的代码实现:
public interface ISomeOperation
{
string DisplayPage(int status);
}
public class Type : ISomeOperation
{
public string DisplayPage(int status)
{
if (status == 1)
return "1";
return string.Empty;
}
}
public class TypeA : ISomeOperation
{
public string DisplayPage(int status)
{
if (status == 2)
return "2A";
if (status == 3)
return "3A";
if (status == 4)
return "4A";
return string.Empty;
}
}
public class TypeB: ISomeOperation
{
public string DisplayPage(int status)
{
if (status == 2)
return "2B";
if (status == 3)
return "3B";
if (status == 4)
return "4B";
return string.Empty;
}
}
public class TypeC : ISomeOperation
{
public string DisplayPage(int status)
{
if (status == 2)
return "2C";
if (status == 3)
return "3C";
if (status == 4)
return "4C";
return string.Empty;
}
}
public class OperationContext
{
private readonly ISomeOperation _iSomeOperation;
public OperationContext(ISomeOperation someOperation)
{
_iSomeOperation = someOperation;
}
public string DisplayPageResult(int status)
{
return _iSomeOperation.DisplayPage(status);
}
}司机代码:
class Program
{
static void Main(string[] args)
{
var operationContext = new OperationContext(new Type());
operationContext.DisplayPageResult(1);
operationContext = new OperationContext(new TypeB());
operationContext.DisplayPageResult(2);
operationContext.DisplayPageResult(3);
operationContext.DisplayPageResult(4);
operationContext = new OperationContext(new TypeC());
operationContext.DisplayPageResult(2);
operationContext.DisplayPageResult(3);
operationContext.DisplayPageResult(4);
}
}发布于 2017-11-02 01:02:03
您的问题陈述要求似乎是创建页面,因此策略可能不适合(关于不改变状态的算法系列)。如果页面的类型是有限的,静态工厂或Prototype (如果您需要克隆每个页面实例)将更适合(有两个用于选择的键)。
https://stackoverflow.com/questions/47046296
复制相似问题