Java 完全使用接口取代了委托功能。
以前面的模板方法举列,通过接口也能实现方法的可替换。
class Program
{
static void Main(string[] args)
{
IProductFactory pizzaFactory = new PizzaFactory();
IProductFactory toycarFactory = new ToyCarFactory();
WrapFactory wrapFactory = new WrapFactory();
Box box1 = wrapFactory.WrapProduct(pizzaFactory);
Box box2 = wrapFactory.WrapProduct(toycarFactory);
Console.WriteLine(box1.Product.Name);
Console.WriteLine(box2.Product.Name);
}
}
interface IProductFactory //声明一个接口,接口只有一个方法
{
Product Make();
}
class PizzaFactory : IProductFactory //这个类是Pizaa加工工厂,实现了IProductFactory接口
{
public Product Make()
{
Product product = new Product();
product.Name = "Pizza";
return product;
}
}
class ToyCarFactory : IProductFactory
{
public Product Make()
{
Product product = new Product();
product.Name = "Toy Car";
return product;
}
}
class Product //产品
{
public string Name { get; set; }
}
class Box //包装产品的盒子
{
public Product Product { get; set; }
}
class WrapFactory //把产品包上盒子交给用户
{
public Box WrapProduct(IProductFactory productFactory)
{
Box box = new Box();
Product product = productFactory.Make();
box.Product = product;
return box;
}
}