博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
面向对象2
阅读量:6158 次
发布时间:2019-06-21

本文共 2348 字,大约阅读时间需要 7 分钟。

  hot3.png

题目: 实现一个画板,根据选择,画出不同形状的图形。

自己写的: 1.Shape:

package demo.panel;public abstract class Shape { protected abstract void draw();}

2.圆,正方形

package demo.panel;public class Circle extends Shape{ @Override protected void draw() { System.out.println("now draw a circle!"); }}package demo.panel;public class Rectangle extends Shape { @Override protected void draw() { System.out.println("now draw a rectangle"); }}

实现: 我的:

package demo.panel;import java.io.BufferedReader;import java.io.InputStreamReader;public class Panel { public void selectShape(int shape){ Shape sh=null; switch (shape) { case 0: sh = new Circle(); break; case 1: sh = new Rectangle(); default: break; } if(sh==null){ System.out.println("your input shaple is not find!"); }else{ sh.draw(); } } public static void main(String[] args) throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int shapeType = Integer.parseInt(br.readLine()); Panel panel = new Panel(); panel.selectShape(shapeType); } }

别人的写法: 把selectShape里面独立一个工厂模式,产生图形:

package demo.panel;import java.util.HashMap;import java.util.Map;public class ShapeFactory { public static final int SHAPE_CIRCLE = 0; public static final int SHAPE_RECTANGLE = 1; public static Map
shapeMap = new HashMap
(); static{ shapeMap.put(new Integer(SHAPE_CIRCLE), "Circle"); shapeMap.put(new Integer(SHAPE_RECTANGLE), "Rectangle"); } public static Shape getShape(int shapeType){ String className = shapeMap.get(new Integer(shapeType)); if(className==null) return null; try { return (Shape)Class.forName(className).newInstance(); } catch (Exception e) { return null; } }}package demo.panel;import java.io.BufferedReader;import java.io.InputStreamReader;public class Panel { public void selectShape(int shape){ Shape sh=ShapeFactory.getShape(shape); if(sh==null){ System.out.println("your input shaple is not find!"); }else{ sh.draw(); } } public static void main(String[] args) throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int shapeType = Integer.parseInt(br.readLine()); Panel panel = new Panel(); panel.selectShape(shapeType); }}耦合性最好的:把图形放到配置文件中配置文件:0=Circle 1=Rectangle

转载于:https://my.oschina.net/wrean/blog/118745

你可能感兴趣的文章
飞翔的秘密
查看>>
Red Hat 安装源包出错 Package xxx.rpm is not signed
查看>>
编译安装mysql-5.6.16.tar.gz
查看>>
活在当下
查看>>
每天进步一点----- MediaPlayer
查看>>
PowerDesigner中CDM和PDM如何定义外键关系
查看>>
跨域-学习笔记
查看>>
the assignment of reading paper
查看>>
android apk 逆向中常用工具一览
查看>>
MyEclipse 报错 Errors running builder 'JavaScript Validator' on project......
查看>>
Skip List——跳表,一个高效的索引技术
查看>>
Yii2单元测试初探
查看>>
五、字典
查看>>
前端js之JavaScript
查看>>
Log4J日志配置详解
查看>>
实验7 BindService模拟通信
查看>>
scanf
查看>>
Socket编程注意接收缓冲区大小
查看>>
SpringMVC初写(五)拦截器
查看>>
检测oracle数据库坏块的方法
查看>>