OOPTest

 

//判断两个对象是否相等,可以根据需要覆写equals方法

@Override
public boolean equals(Object obj) {
if(this == obj){
return true;
}
if(obj instanceof Person){
Person p = (Person)obj;
return this.age==p.age && this.name==p.name;
}else{
return false;
}
}

======Line Circle Rectangle==============

package test.oop;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;

public class ShapeTest{
public static void main(String[] args) throws Exception{
new Panel().selectShape();
}
}
//定义画板类
class Panel{
public void selectShape() throws IOException, InstantiationException, IllegalAccessException, ClassNotFoundException{
System.out.println("请输入形状类型:");
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
String readLine = br.readLine();
int shapeType = Integer.parseInt(readLine);
// System.out.println(shapeType);
Shape shape = ShapeFactory.getShape(shapeType);
// System.out.println(shape);
if(shape == null){
System.out.println("输入的图形不存在");
}else{
shape.draw();
}
}
}
//定义图形抽象类
abstract class Shape{
abstract void draw();
}
//定义直线图形
class Line extends Shape{
@Override
void draw() {
System.out.println("Draw a Line");
}
}
//定义图形圆
class Circle extends Shape{
@Override
void draw() {
System.out.println("Draw a Circle");
}
}
//定义图形矩形
class Rectangle extends Shape{
void draw(){
System.out.println("Draw a Rectangle");
}
}
//图形工厂
class ShapeFactory{
public static final int SHAPE_TYPE_LINE=1;
public static final int SHAPE_TYPE_CIRCLE=2;
public static final int SHAPE_TYPE_RECTANGLE=3;
private static Map<Integer,String> shapes = new HashMap<Integer,String>();
static{//初始化工厂
shapes.put(SHAPE_TYPE_LINE, "test.oop.Line");
shapes.put(SHAPE_TYPE_CIRCLE, "test.oop.Circle");
shapes.put(SHAPE_TYPE_RECTANGLE, "test.oop.Rectangle");
}
public static Shape getShape(int type) throws InstantiationException, IllegalAccessException, ClassNotFoundException{
String className = shapes.get(type);
// System.out.println(className);
return (Shape) Class.forName(className).newInstance();
}
}

posted @ 2021-01-28 16:54  geryhz  阅读(48)  评论(0编辑  收藏  举报