考虑下面的示例code:
Considering the following sample code:
// delivery strategies
public abstract class DeliveryStrategy { ... }
public class ParcelDelivery : DeliveryStrategy { ... }
public class ShippingContainer : DeliveryStrategy { ... }
和下面的示例Order类:
and the following sample Order class:
// order (base) class
public abstract class Order
{
private DeliveryStrategy delivery;
protected Order(DeliveryStrategy delivery)
{
this.delivery = delivery;
}
public DeliveryStrategy Delivery
{
get { return delivery; }
protected set { delivery = value; }
}
}
当我得到一个新的类型顺序类,它将继承类型DeliveryStrategy的交付财产。
When i derive a new type of order class, it will inherit the Delivery property of type DeliveryStrategy.
现在,当它被赋予了CustomerOrders必须使用ParcelDelivery策略交付,我们可以考虑'新荷兰国际集团交付物业的CustomerOrder类:
Now, when it is given that CustomerOrders must be delivered using the ParcelDelivery strategy, we could consider 'new'ing the Delivery property in the CustomerOrder class:
public class CustomerOrder : Order
{
public CustomerOrder()
: base(new ParcelDelivery())
{ }
// 'new' Delivery property
public new ParcelDelivery Delivery
{
get { return base.Delivery as ParcelDelivery; }
set { base.Delivery = value; }
}
}
(该CustomerOrder显然需要确保兼容(多形体)与订单)
(The CustomerOrder obviously needs to ensure that is compatible (polymorph) with Order)
此允许在CustomerOrder的ParcelDelivery策略直接使用而不需要铸造
This allows direct usage of the ParcelDelivery strategy on CustomerOrder without the need for casting.
你会考虑使用这种模式?为什么/为什么不呢?
Would you consider using this pattern? why / why not?
更新:我来了,而不是使用泛型,因为我想用这个为多个属性了这种模式。我不希望使用泛型类型参数对所有这些特性
Update: i came up with this pattern, instead of using generics, because i want to use this for multiple properties. I don't want to use generic type arguments for all these properties
推荐答案
我觉得这是一个很好的模式。这使得它更容易明确地不再需要把结果用派生类型,并且它不破发的基类的行为。其实,类似的模式被用在一些班级在BCL,例如看的DbConnection类层次:
I think this is a good pattern. It makes it easier to explicitly use derived types by removing the need to cast the result, and it doesn't 'break' the base class behavior. Actually, a similar pattern is used in some classes in the BCL, for instance look at the DbConnection class hierarchy :
DbConnection.CreateCommand()返回的DbCommand SqlConnection.CreateCommand()隐藏了使用新的返回一个SqlCommand基实现。 (其他的DbConnection实现都一样)所以,如果你通过的DbConnection变量操作连接对象,CreateCommand将返回的DbCommand;如果你通过一个SqlConnection变量操纵它,CreateCommand会返回一个SqlCommand,避免投,如果你将它赋值给一个SqlCommand变量。
So, if you manipulate the connection object through a DbConnection variable, CreateCommand will return a DbCommand ; if you manipulate it through a SqlConnection variable, CreateCommand will return a SqlCommand, avoiding the cast if you're assigning it to a SqlCommand variable.
相关推荐
最新文章