java代码实现设计模式
时间: 2023-10-14 21:06:27 浏览: 41
Java 中常见的设计模式有很多,下面列举几个比较常用的设计模式,并附上相应的 Java 代码实现:
1. 工厂模式
工厂模式是一种创建型设计模式,它用于创建对象而不需要指定具体类。在工厂模式中,我们创建对象而不是直接实例化对象,从而将类的实例化推迟到子类中。
```
interface Shape {
void draw();
}
class Circle implements Shape {
@Override
public void draw() {
System.out.println("Circle draw()");
}
}
class Square implements Shape {
@Override
public void draw() {
System.out.println("Square draw()");
}
}
class ShapeFactory {
public Shape getShape(String shapeType) {
if (shapeType == null) {
return null;
}
if (shapeType.equalsIgnoreCase("CIRCLE")) {
return new Circle();
} else if (shapeType.equalsIgnoreCase("SQUARE")) {
return new Square();
}
return null;
}
}
public class FactoryPatternDemo {
public static void main(String[] args) {
ShapeFactory shapeFactory = new ShapeFactory();
Shape circle = shapeFactory.getShape("CIRCLE");
circle.draw();
Shape square = shapeFactory.getShape("SQUARE");
square.draw();
}
}
```
2. 单例模式
单例模式是一种创建型设计模式,它保证一个类只有一个实例,并提供一个全局点访问该实例的方式。
```
class Singleton {
private static Singleton instance = new Singleton();
private Singleton() {}
public static Singleton getInstance() {
return instance;
}
public void showMessage() {
System.out.println("Hello World!");
}
}
public class SingletonPatternDemo {
public static void main(String[] args) {
Singleton instance = Singleton.getInstance();
instance.showMessage();
}
}
```
3. 装饰器模式
装饰器模式是一种结构型设计模式,它允许我们动态地添加功能到对象中。在装饰器模式中,我们将对象包装在一个装饰器类中,并且在运行时添加功能。
```
interface Shape {
void draw();
}
class Circle implements Shape {
@Override
public void draw() {
System.out.println("Circle draw()");
}
}
class Square implements Shape {
@Override
public void draw() {
System.out.println("Square draw()");
}
}
abstract class ShapeDecorator implements Shape {
protected Shape decoratedShape;
public ShapeDecorator(Shape decoratedShape) {
this.decoratedShape = decoratedShape;
}
public void draw() {
decoratedShape.draw();
}
}
class RedShapeDecorator extends ShapeDecorator {
public RedShapeDecorator(Shape decoratedShape) {
super(decoratedShape);
}
public void draw() {
decoratedShape.draw();
setRedBorder(decoratedShape);
}
private void setRedBorder(Shape decoratedShape) {
System.out.println("Border Color: Red");
}
}
public class DecoratorPatternDemo {
public static void main(String[] args) {
Shape circle = new Circle();
Shape redCircle = new RedShapeDecorator(new Circle());
Shape redSquare = new RedShapeDecorator(new Square());
circle.draw();
redCircle.draw();
redSquare.draw();
}
}
```
以上是三种常见的设计模式的 Java 实现,如果需要了解更多设计模式,可以参考《Head First 设计模式》一书。