lintcode:形状工厂
2016-07-07 16:43
288 查看
题目工厂模式是一种常见的设计模式。实现一个形状工厂
ShapeFactory来创建不同的形状类。这里我们假设只有三角形,正方形和矩形三种形状。样例
ShapeFactory sf = new ShapeFactory(); Shape shape = sf.getShape("Square"); shape.draw(); >> ---- >> | | >> | | >> ---- shape = sf.getShape("Triangle"); shape.draw(); >> /\ >> / \ >> /____\ shape = sf.getShape("Rectangle"); shape.draw(); >> ---- >> | | >> ---- 解题 直接draw方法
/** * Your object will be instantiated and called as such: * ShapeFactory sf = new ShapeFactory(); * Shape shape = sf.getShape(shapeType); * shape.draw(); */ interface Shape { void draw(); } class Rectangle implements Shape { // Write your code here public void draw(){ System.out.println(" ----"); System.out.println("| |"); System.out.println(" ----"); } } class Square implements Shape { // Write your code here public void draw(){ System.out.println(" ----"); System.out.println("| |"); System.out.println("| |"); System.out.println(" ----"); } } class Triangle implements Shape { // Write your code here public void draw(){ System.out.println(" /\\"); System.out.println(" / \\"); System.out.println("/____\\"); } } public class ShapeFactory { /** * @param shapeType a string * @return Get object of type Shape */ public Shape getShape(String shapeType) { // Write your code here if(shapeType.equals("Square")){ return new Square(); } if(shapeType.equals("Rectangle")){ return new Rectangle(); } if(shapeType.equals("Triangle")){ return new Triangle(); } return null; } }
相关文章推荐
- jqgird 设置多选 只能选中 最后一行 选不中鼠标点击的一行
- UI里面excel数据上传并解析的例子(CSV格式)
- SQL Server的优化
- 动态规划
- Android开发之Intent.Action
- MySQL传智播客--Lession25-Lession30笔记
- android Toolbar的封装
- Nodejs中关于类的创建
- windows共享文件删除记录审核
- 结构体和类的区别
- HDU4403 dfs
- EditText焦点的问题。
- 播布客
- Swift之控件-UIlabel
- 【ArcGis for javascript从零开始】之一 ArcGis加载天地图
- centos编译helloworld的几个小问题
- PopupWindow的使用
- 宏定义 #,##
- 9、利用Hessian和Spring整合开发WebService服务
- flume+kafka+storm+redis+mongodb 配置