0

这是一个家庭作业问题。

我有以下问题:我需要创建一个系统,可以根据房东的类型和租户的类型模拟房东向租户征税或收费的方式。房东可以是低级房东(管理一个破烂的公寓楼),一个中级房东(管理一个马马虎虎的楼)和一个高级房东(管理一个顶级楼)。租户可以是不负责任的租户(延迟几个月付款)或负责任的租户(按时付款)。

根据房东的种类有固定的资费,根据租户的种类和房东的种类给予罚款或福利:不负责任的租户将被收取额外费用,负责任的租户将获得一些奖金早或其他,但这仅适用于他住在由高级房东或中级房东管理的建筑物中。租户应该有一个属性来存储它必须支付的租金。

我以这种方式绘制了这个问题:

  • 一个 Landlord 抽象类,具有以下继承自它的具体类:High Class、Low Class 和 Middle Class。
  • 一个租户抽象类,具有不负责任和负责任的具体后代。

我的问题是如何实现向租户收费的方法?我提出了以下建议:Landlord 类定义了一个名为 chargeTheTenant() 的虚拟方法,它接受类 Tenant 的参数,并根据租户的类型对其进行收费。问题是,为此我必须使用反射来找出 Landlord 类的租户类型,并且我被告知我必须尽量不要使用反射,并且我应该搜索设计模式来解决这个问题.

我应该研究什么设计模式以避免在这种情况下使用反射?

谢谢

4

2 回答 2

0

That's a scenario for the Strategy pattern. Anyways, it something like this (C# ahead)

public interface IChargeRent
{
      void Chanrge(Tenant tenant);
}

public class HighClassPropertyRentCollector:IChargeRent
{
     //we assume this object contains or it gets the tarrifs

     public void Charge(Tenant tenant)
     {
          if (tenant.IsIrresponsible) { //apply penalty
              }
             else{ //whatever }
     }
}


public class MiddleClassPropertyRentCollector:HighClassPropertyRentCollector {}

public class LowClassPropertyRentCollector:IChargeRent
{
     public void Charge(Tenant tenant) {

      }
 }

   public interface ICanChargeRent
   {
       PropertyClassType PropetyLevel {get;}
   }

   public class Landlord:ICanChargeRent { }

 //in another class
 public static IChargeRent GetRentCollector(ICanChargeRent ll)
 {
       //switch on PropertyLevel and instantiate the corresponding rent charger
  }

Middle landlords have, for now, the same behaviour as the high class landlords so that's why I inherit from high class landlords, however that could change so its better to have an explicit rent charging strategy for each landlord. Same for low class landlords.

If there is a certain way to determine the quality of the tenant, then each will get injected a service which will provide that funcitonality. And because the rent charging behaviour is encapsulated their own classes, you can change it without needing to change the Landlord.

The reason my solution is different from your proposal is that charging rent is not really part of what defines a Landlord (yes, I know how it sounds) but a use case of a landlord. After all, if the landlord hires a property manager and tells him to charge rent, does the definition of a landlord changes? Not so much.

Even in this scenario 99% of the code I wrote works unchanged. You only need to make the PropertyManager implement ICanChargeRent while removing the interface from the Landlord. And we can come up with an even more maintainable solution (requiring less changes) if we know more details about the domain.

于 2013-11-08T08:42:51.543 回答
0

在这种情况下,租户抽象类可能是过度抽象的标志。如果只使用一个Tenant类,方法IsIrresponsible (),楼主可以直接根据这个方法的返回来做决定。

如果您坚持使用抽象租户类,只需将IsIrresponsible () 函数设为虚拟即可。并且总是在IrresponsibleTenant子类中返回 true,在ResponsibleTenant子类中返回 false。但个人认为不值得。

于 2013-11-08T07:57:40.810 回答