---
title: "开闭原则"
author: "memorymyann"
date: "2011-12-13T15:01:23Z"
tags: []
categories: ["非技术"]
slug: "untitled"
draft: false
lastmod: "2011-12-21T14:09:22Z"
id: 1308657
url: "https://memorymyann.iteye.com/blog/1308657"
---

开闭原则：对扩展开放，对修改关闭。或者换句话来说就是一个模块在不被修改的前提下可以被扩展。

 

说的有点抽象，至少不是那么容易去理解，我举个例子来理解下，如果写的有误也欢迎各位指出。

我有个抽象的图形类如下

package sty;

public abstract class Graph {  
    //获取图形面积，这里只返回整数  
    public abstract int getArea();  
}  
具体的求面积的实现是根据图形的形状来确定的，比如我有以下几个具体的图形类

package sty;

//圆  
public class Circle extends Graph {  
    //半径  
    private int radius;   

    public int getRadius() {  
        return radius;  
    }

    public void setRadius(int radius) {  
        this.radius = radius;  
    }

    public int getArea() {  
        return 3 * radius * radius;  
    }

}

 

package sty;  
//三角形  
public class Triangle extends Graph {  
    //底边长  
    public int bottom;  
    //高  
    public int height;  
     
   

    public int getBottom() {  
        return bottom;  
    }

    public void setBottom(int bottom) {  
        this.bottom = bottom;  
    }

    public int getHeight() {  
        return height;  
    }

    public void setHeight(int height) {  
        this.height = height;  
    }

    @Override  
    public int getArea() {  
        return bottom * height / 2;  
    }

}

这符合大多数人的设计逻辑，这里就反映了一种开闭原则。首先对于求面积的方法public abstract int getArea();这种形式我们是不会改变的，但他具体的实现则取决于具体的图形，具体实现这部分是可以扩展的。（不知道我这里例子举的恰当否？）

 

那么在这种原则下，对我们编码产生的影响如下：

Graph g = new xxx(); //这里可能是三角，也可能是圆，但无论哪种具体的实现类,对我么求面积来说并没有什么不同

......

g.getArea();

 

顺便给出一个介绍设计原则的文章http://www.kuqin.com/design-patterns/20080727/12537.html