设计模式的七大原则——开闭原则(上)

开闭原则:   当软件需要变化时,尽量通过扩展软件实体的行为来实现变化,而不是通过修改

有的代码来实现变化。

开闭原则代码1:(未能遵循开闭原则,存在优化的空间)

/**
 * 开闭原则代码1
 */
public class oncg {

	public static void main(String[] args) {

		GraphicEditor graphicEditor = new GraphicEditor();

		graphicEditor.drawShape(new Rectangle());
		graphicEditor.drawShape(new Circle());
		graphicEditor.drawShape(new Triangle());
	}

}

/**
 * 用于绘图的类[使用方]
 */
class GraphicEditor {

	// 接收 Shape 对象,然后根据 type, 来绘制不同的图形
	public void drawShape(Shape s) {

		if (s.m_typte == 1) {
			drawRectangle(s);
		} else if (s.m_typte == 2) {
			drawCircle(s);
		} else if (s.m_typte == 3) {
			drawTriangle(s);
		}
	}

	// 绘制矩形
	public void drawRectangle(Shape s) {
		System.out.println(" 绘制矩形 ");
	}

	// 绘制圆形
	public void drawCircle(Shape s) {
		System.out.println(" 绘制圆形 ");
	}

	public void drawTriangle(Shape s) {
		System.out.println(" 绘制三角形 ");
	}
}

/**
 * Shape类,基类
 */
class Shape {
	int m_typte;
}

/**
 * 矩形实体类
 */
class Rectangle extends Shape {

	Rectangle() {
		super.m_typte = 1;
	}

}

/**
 * 圆形实体类
 */
class Circle extends Shape {

	Circle() {
		super.m_typte = 2;
	}

}

/**
 * 三角形实体类
 */
class Triangle extends Shape {

	Triangle() {
	    super.m_typte = 3;
	}

}

解析:违反了OCP原则,新增一个新的类,比如三角形,我们需要修改的地方较多;优化方案将使用ocp原则,请看下篇;

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值