帮我写一个SOLID原则伪代码示例
时间: 2023-08-20 15:31:49 浏览: 40
好的,以下是一个简单的伪代码示例,展示如何使用SOLID原则来设计一个简单的图形绘制程序:
```
// 单一职责原则示例
class Rectangle {
int width;
int height;
public void setWidth(int w) {
width = w;
}
public void setHeight(int h) {
height = h;
}
public int getArea() {
return width * height;
}
}
class Circle {
int radius;
public void setRadius(int r) {
radius = r;
}
public int getArea() {
return (int) (Math.PI * radius * radius);
}
}
class GraphicsRenderer {
public void render(Rectangle r) {
// 绘制矩形
}
public void render(Circle c) {
// 绘制圆形
}
}
// 开放封闭原则示例
interface Shape {
int getArea();
}
class Rectangle implements Shape {
int width;
int height;
public void setWidth(int w) {
width = w;
}
public void setHeight(int h) {
height = h;
}
public int getArea() {
return width * height;
}
}
class Circle implements Shape {
int radius;
public void setRadius(int r) {
radius = r;
}
public int getArea() {
return (int) (Math.PI * radius * radius);
}
}
class GraphicsRenderer {
public void render(Shape s) {
// 绘制图形
}
}
// 里氏替换原则示例
class Square extends Rectangle {
@Override
public void setWidth(int w) {
super.setWidth(w);
super.setHeight(w);
}
@Override
public void setHeight(int h) {
super.setWidth(h);
super.setHeight(h);
}
}
// 接口隔离原则示例
interface Drawable {
void draw();
}
interface Scalable {
void scale(int factor);
}
class Rectangle implements Drawable, Scalable {
// 实现 draw() 和 scale() 方法
}
class Circle implements Drawable, Scalable {
// 实现 draw() 和 scale() 方法
}
// 依赖倒置原则示例
interface ShapeRenderer {
void render(Shape s);
}
class GraphicsRenderer implements ShapeRenderer {
public void render(Shape s) {
// 绘制图形
}
}
class Shape {
int getArea();
}
class Rectangle implements Shape {
int width;
int height;
public void setWidth(int w) {
width = w;
}
public void setHeight(int h) {
height = h;
}
public int getArea() {
return width * height;
}
}
class Circle implements Shape {
int radius;
public void setRadius(int r) {
radius = r;
}
public int getArea() {
return (int) (Math.PI * radius * radius);
}
}
class Drawing {
private ShapeRenderer renderer;
private List<Shape> shapes;
public Drawing(ShapeRenderer r) {
renderer = r;
shapes = new ArrayList<>();
}
public void addShape(Shape s) {
shapes.add(s);
}
public void draw() {
for (Shape s : shapes) {
renderer.render(s);
}
}
}
```