我正在为一个邻居做一个小的申请,目前我对这个设计非常困惑。一开始看上去很简单,但现在我被困住了。我理解遗产,因此,
场景:用户以其身份给商店送礼物(例如,给家人的礼物,给同事的礼物)。因此,有一个生日礼物是给一个同事,这是不同的礼物,一个家庭。用户指定他们喜欢使用的包装样式。(例如,折纸,西方)在这种情况下,假设给同事的生日礼物必须用折纸包装的生日风格。
但是我怎么把礼物和包装联系起来呢?一开始,包装在我看来像是一个界面。所以一个礼物实现了它。但是,包装每一种主要的包装样式都有子包装风格,这使得它变得复杂。同事的生日礼物如何知道要实现哪个接口?这似乎是生日,婚礼也应该是抽象的课程,因为只有第三代礼物课是一个具体的课程。
,我如何才能让这个设计变得有意义,但现在就很容易编写代码,并在以后有修改/改进的空间呢?

发布于 2014-11-01 03:29:48
为了将每个礼物与包装相关联,您可以做而不是来实现包装。那是行不通的。相反,将包装作为一个变量包含在Gift中。
您的方法似乎是使用抽象类(本质上是部分实现):
public abstract class Gift
{
public IWrappingStyle wrapping { get; private set; }
public Gift(IWrappingStyle wrapping)
{
this.wrapping = wrapping;
}
public void Unwrap()
{
// code common to all gifts for unwrapping
// ...
}
}
public interface IWrappingStyle
{
}然后,您可以继续将第二级类型表示为包装样式的接口和用于礼物的抽象类,将类表示为其他所需类型的最低级别。添加一个新类就像添加一个新类一样简单。
然后,你可以这样做:
Gift g = new GraduationSchoolGift(new OrigamiBirthdayWrapping());别忘了使用文件夹!

但是,除非您对于不同的包装有一些特定的不同行为,否则我认为您可以使用一个更简单的布局:
public class Gift
{
public String GiftType { get; private set; }
public String WrappingStyle { get; private set; }
public Gift(String giftType, String wrappingStyle)
{
this.GiftType = giftType;
this.WrappingStyle = wrappingStyle;
}
}然后,如果您(再次)将文件组织在如下文件夹中:

下面是各自的文件(名称空间很重要):
礼品类型:
namespace GiftWrapping.GiftTypes
{
public class Birthday
{
public static const String FIFTH_BIRTHDAY = "Birthday Fifth";
public static const String TENTH_BIRTHDAY = "Birthday Tenth";
}
}
namespace GiftWrapping.GiftTypes
{
public class Wedding
{
public static const String FAMILY = "Wedding Family";
public static const String FRIENDS = "Wedding Friends";
}
}包装样式:
namespace GiftWrapping.WrappingStyles
{
public class Origami
{
public static const String BIRTHDAY = "Origami Birthday";
public static const String WEDDING = "Origami Wedding";
}
}
namespace GiftWrapping.WrappingStyles
{
public class Western
{
public static const String SCHOOL = "Western School";
public static const String WEDDING = "Western Wedding";
public static const String UNIVERSITY = "Western University";
}
}现在使用情况如下:
Gift g = new Gift(GiftTypes.Wedding.FAMILY,
WrappingStyles.Origami.BIRTHDAY);发布于 2014-11-01 03:37:02
实际上,编写一个接口是一个很好的实践。当您编写单元测试时,它们确实可以帮助您,并且是坚实的基础。所以你可以尝试这样的方法:
public interface IGift
{
public void Wrap(IWrappingStyle wrappingStyle)
{
}
}
public interface IWrappingStyle
{
}有了这种对象依赖关系,您可以使用一些类似的策略模式来根据类的类型来处理包装样式。
发布于 2014-11-01 03:35:27
礼品和包装是分开的实体,使用依赖注入。
Class wrapping{
protected $gift;
public __construct( $gift ){
$this->gift = $gift
}
public getGift(){
return $this->gift;
}
}
Class gift{
}
$g = new gift()
$w = new wrapper($g);这样你就不需要改变每一个新礼物的包装,或者每一个新包装的礼物。无论是接口礼物,还是使其抽象,都取决于功能。包装也是如此。不要将它们混合在“代码”级别,即使上面的图表显示它们是单独的对象。
就我个人而言,我要么会接口礼物,要么为它创建一个基本的抽象类。然后,你可以依靠未来的礼物,有你需要的代码包装。
哈刚刚意识到这是C,我是怎么做到的。无论如何,这个想法是一样的,即使它不是PHP。
干杯。
https://stackoverflow.com/questions/26685942
复制相似问题