设计模式之工厂模式
2015-07-27 22:02
309 查看
工厂模式是比较简单,也是比较好用的一种方式。根本上说,工厂模式的目的就根据不同的要求输出不同的产品。比如说吧,有一个生产鞋子的工厂,它能生产皮鞋,也能生产胶鞋。如果用代码设计,应该怎么做呢?
怎么使用这个工厂呢?我们来写下面的代码:
public interface Shoe { } public class Leather_Shoe:Shoe { public Leather_Shoe() { Console.WriteLine("This is a leather show!\n""); } } public class Rubber_Shoe:Shoe { public Rubber_Shoe() { Console.WriteLine(""This is a rubber shoe!\n""); } }我们的ShoeFactory应该是怎么样呢?
public class ShoeFactory { public Leather_Shoe MakeLeather_Shoe() { return new Leather_Shoe(); } public Rubber_Shoe MakeRubber_Shoe() { return new Rubber_Shoe(); } }
怎么使用这个工厂呢?我们来写下面的代码:
string ShoeName = Console.ReadLine(); Shoe MyShoe = null; ShoeFactory MyShoeFactory = new MyShoeFactory(); switch (ShoeName) { case "Leather_Shoe": MyShoe = MyShoeFactory.MakeLeather_Shoe(); break; case "Rubber_Shoe": MyShoe = MyShoeFactory.MakeRubber_Shoe(); break; default: break; }
相关文章推荐
- 使用python内置pip工具来安装wheel文件
- Android编程规范与常用技巧
- 用二维码扫描
- JavaScript call和apply的用法
- Balanced and stabilized quicksort method
- Lintcode 主元素
- ACM/ICPC World Finals 2012 D Fibonacci Words
- Where is the Marble?
- 关于sacnf的使用
- 通过SpringMVC+Annotation实现方法、按钮级别的细粒度权限控制
- iOS注意事项
- Android Acitivy切换平移动画效果实现
- 精通Hibernate——Hibernate内置标识符详解
- SAP ABAP 它已被释放TR(或任务),减少的变化TR(任务),删除释放TR(任务)
- Binary Tree Level Order Traversal
- ZOJ1654 Place the Robots (二分图匹配)
- 数据库事务(写得比较到位)
- V4包的经常错误
- POJ 2446 Chessboard
- zoj 3888 Twelves Monkeys 二分+线段树维护次小值