新手问题:Java类有一个成员变量,它是一种接口类型.有人能澄清吗



有人能为我指明正确的方向吗。我正在学习策略模式(在维基百科上(,在代码示例中,有一些我不理解的地方。

public IBillingStrategy Strategy的线路这是什么?

class Customer {
// Get/Set Strategy
public IBillingStrategy Strategy { get; set; }  // <---- This confuses me
public Customer(IBillingStrategy strategy) {
this.drinks = new List<double>();
this.Strategy = strategy;
}
// code that I omitted
}
interface IBillingStrategy {
double GetActPrice(double rawPrice);
}

我知道你不能实例化接口的实例。我知道类是用来实现带有关键字的接口的。我知道那叫什么,但我在谷歌搜索中失败了。

首先,这不是Java。你不能在Java中写这样的getter-setter方法:(这是C#(

public IBillingStrategy Strategy { get; set; }

其次,如果你向下滚动,你会看到这个界面的实现:

class NormalStrategy : IBillingStrategy
{
public double GetActPrice(double rawPrice) => rawPrice;
}
class HappyHourStrategy : IBillingStrategy
{
public double GetActPrice(double rawPrice) => rawPrice * 0.5;
}

因此,这基本上是代码到接口模式。这基本上意味着,您设计Customer类的方式是,Customer的实例可以将NormalStrategy或HappyHourStrategy作为其实例变量。

因此,如果你看到主要的方法:

var firstCustomer = new Customer(normalStrategy);

第一个客户是拥有NormalStrategy(不是快乐时光(的客户。

而第二个客户是拥有HappyHourStrategy的客户。

Customer secondCustomer = new Customer(happyHourStrategy);

因此,对于您的疑问:我知道你不能实例化接口的实例

你是绝对正确的。那么这是怎么回事呢?答案是:实现是通过构造函数或方法调用注入到代码中的。

在这里,它是通过构造函数注入的。

var normalStrategy    = new NormalStrategy();
var firstCustomer = new Customer(normalStrategy);

因此,您的代码了解接口或抽象类,并且可以调用此约定中定义的任何内容。

这是利斯科夫替代原理(LSP(的子集,即SOLID原理的L。

相关内容

最新更新