Java 完全使用接口取代了委托功能。

    以前面的模板方法举列,通过接口也能实现方法的可替换。

    1. class Program
    2. {
    3. static void Main(string[] args)
    4. {
    5. IProductFactory pizzaFactory = new PizzaFactory();
    6. IProductFactory toycarFactory = new ToyCarFactory();
    7. WrapFactory wrapFactory = new WrapFactory();
    8. Box box1 = wrapFactory.WrapProduct(pizzaFactory);
    9. Box box2 = wrapFactory.WrapProduct(toycarFactory);
    10. Console.WriteLine(box1.Product.Name);
    11. Console.WriteLine(box2.Product.Name);
    12. }
    13. }
    14. interface IProductFactory //声明一个接口,接口只有一个方法
    15. {
    16. Product Make();
    17. }
    18. class PizzaFactory : IProductFactory //这个类是Pizaa加工工厂,实现了IProductFactory接口
    19. {
    20. public Product Make()
    21. {
    22. Product product = new Product();
    23. product.Name = "Pizza";
    24. return product;
    25. }
    26. }
    27. class ToyCarFactory : IProductFactory
    28. {
    29. public Product Make()
    30. {
    31. Product product = new Product();
    32. product.Name = "Toy Car";
    33. return product;
    34. }
    35. }
    36. class Product //产品
    37. {
    38. public string Name { get; set; }
    39. }
    40. class Box //包装产品的盒子
    41. {
    42. public Product Product { get; set; }
    43. }
    44. class WrapFactory //把产品包上盒子交给用户
    45. {
    46. public Box WrapProduct(IProductFactory productFactory)
    47. {
    48. Box box = new Box();
    49. Product product = productFactory.Make();
    50. box.Product = product;
    51. return box;
    52. }
    53. }