- public class OCP {
-
- public static void main(String[] args) {
- // 使用看看存在的问题
- GraphEditor graphEditor = new GraphEditor();
- graphEditor.drawShape(new Rectangle());
- graphEditor.drawShape(new Circle());
- graphEditor.drawShape(new Triangle());
-
- }
-
- }
-
- // 这是一个用于绘图的类[使用方]
- class GraphEditor {
-
- // 接收Shape对象,然后根据type,来绘制不同的图形
- public void drawShape(Shape s){
- if (s.mType == 1){
- drawRectangle(s);
- }else if (s.mType == 2){
- drawCircle(s);
- }else if (s.mType == 3){
- drawTriangle(s);
- }
- }
-
- // 绘制矩形
- public void drawRectangle(Shape r){
- System.out.println("绘制矩形");
- }
-
- // 绘制圆形
- public void drawCircle(Shape r){
- System.out.println("绘制圆形");
- }
-
- // 绘制三角形
- public void drawTriangle(Shape r){
- System.out.println("绘制三角形");
- }
-
- }
-
- // Shape类,基类
- class Shape {
- int mType;
- }
- // 矩形类
- class Rectangle extends Shape {
- public Rectangle() {
- super.mType = 1;
- }
- }
-
- // 圆形类
- class Circle extends Shape {
- public Circle() {
- super.mType = 2;
- }
- }
-
- // 新增三角形
- class Triangle extends Shape{
- public Triangle(){
- super.mType = 3;
- }
- }
- public class OCP {
-
- public static void main(String[] args) {
- // 使用看看存在的问题
- GraphEditor graphEditor = new GraphEditor();
- graphEditor.drawShape(new Rectangle());
- graphEditor.drawShape(new Circle());
- graphEditor.drawShape(new Triangle());
- graphEditor.drawShape(new OtherGraphic());
-
- }
-
- }
-
- // 这是一个用于绘图的类[使用方]
- class GraphEditor {
-
- // 接收Shape对象,调用draw方法
- public void drawShape(Shape s){
- s.draw();
- }
-
- }
-
- // Shape类,基类
- abstract class Shape {
- int mType;
- public abstract void draw();
- }
- // 矩形类
- class Rectangle extends Shape {
- public Rectangle() {
- super.mType = 1;
- }
-
- @Override
- public void draw() {
- System.out.println("绘制矩形");
- }
- }
-
- // 圆形类
- class Circle extends Shape {
- public Circle() {
- super.mType = 2;
- }
-
- @Override
- public void draw() {
- System.out.println("绘制圆形");
- }
- }
-
- // 新增三角形
- class Triangle extends Shape{
- public Triangle(){
- super.mType = 3;
- }
-
- @Override
- public void draw() {
- System.out.println("绘制三角形");
- }
- }
-
- // 新增一个图形
- class OtherGraphic extends Shape{
-
- public OtherGraphic(){
- super.mType = 4;
- }
-
- @Override
- public void draw() {
- System.out.println("绘制其它图形");
- }
- }