Java后端八股------设计模式

本文深入探讨了设计模式中的工厂方法和抽象工厂模式,通过Java代码示例详细解释了如何使用这些模式来创建对象,展示了产品接口、具体产品、工厂接口和具体工厂的实现方式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在这里插入图片描述在这里插入图片描述

Coffee可以设计成接口。
在这里插入图片描述

示例:

// 产品接口
interface Product {
    void use();
}

// 具体产品
class ConcreteProductA implements Product {
    public void use() {
        System.out.println("Using ConcreteProductA");
    }
}

class ConcreteProductB implements Product {
    public void use() {
        System.out.println("Using ConcreteProductB");
    }
}

// 简单工厂类
class SimpleFactory {
    public static Product createProduct(String type) {
        if (type == null) {
            return null;
        }
        if (type.equalsIgnoreCase("A")) {
            return new ConcreteProductA();
        } else if (type.equalsIgnoreCase("B")) {
            return new Product(new ConcreteProductB());
        }
        return null;
    }
}

// 客户端代码
public class SimpleFactoryDemo {
    public static void main(String[] args) {
        Product product = SimpleFactory.createProduct("A");
        product.use();
    }
}

在这里插入图片描述
示例:

// 产品接口
interface Product {
    void use();
}

// 具体产品
class ConcreteProductA implements Product {
    public void use() {
        System.out.println("Using ConcreteProductA");
    }
}

class ConcreteProductB implements Product {
    public void use() {
        System.out.println("Using ConcreteProductB");
    }
}

// 工厂接口
interface Factory {
    Product createProduct();
}

// 具体工厂
class ConcreteFactoryA implements Factory {
    public Product createProduct() {
        return new ConcreteProductA();
    }
}

class ConcreteFactoryB implements Factory {
    public Product createProduct() {
        return new ConcreteProductB();
    }
}

// 客户端代码
public class FactoryMethodDemo {
    public static void main(String[] args) {
        Factory factory = new ConcreteFactoryA();
        Product product = factory.createProduct();
        product.use();
    }
}

抽象工厂模式

// 产品接口
interface Product {
    void use();
}

// 具体产品
class ConcreteProductA implements Product {
    public void use() {
        System.out.println("Using ConcreteProductA");
    }
}

class ConcreteProductB implements Product {
    public void use() {
        System.out.println("Using ConcreteProductB");
    }
}

// 抽象工厂接口
interface AbstractFactory {
    Product createProduct();
}

// 具体工厂
class ConcreteFactory implements AbstractFactory {
    public Product createProduct() {
        // 决定创建哪种产品
        return new ConcreteProductA();
    }
}

// 客户端代码
public class AbstractFactoryDemo {
    public static void main(String[] args) {
        AbstractFactory factory = new ConcreteFactory();
        Product product = factory.createProduct();
        product.use();
    }
}

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

单例

应用:线程池、数据库连接池、日志记录等。

饿汉式(线程安全)
public class HungrySingleton {
    private static final HungrySingleton instance = new HungrySingleton();

    private HungrySingleton() {}

    public static HungrySingleton getInstance() {
        return instance;
    }
}
懒汉式
public class LazySingleton {
    private static LazySingleton instance;

    private LazySingleton() {}

    public static synchronized LazySingleton getInstance() {
        if (instance == null) {
            instance = new LazySingleton();
        }
        return instance;
    }
}
双重检查锁定(DCL)–线程安全
public class DoubleCheckedLockingSingleton {
    private static volatile DoubleCheckedLockingSingleton instance;

    private DoubleCheckedLockingSingleton() {}

    public static DoubleCheckedLockingSingleton getInstance() {
        if (instance == null) {
            synchronized (DoubleCheckedLockingSingleton.class) {
                if (instance == null) {
                    instance = new DoubleCheckedLockingSingleton();
                }
            }
        }
        return instance;
    }
}
静态内部类
public class StaticInnerClassSingleton {
    private StaticInnerClassSingleton() {}

    private static class Holder {
        private static final StaticInnerClassSingleton INSTANCE = new StaticInnerClassSingleton();
    }

    public static StaticInnerClassSingleton getInstance() {
        return Holder.INSTANCE;
    }
}

工厂方法

简单工厂

例子:

// 图形接口
public interface Shape {
    void draw();
}
// 圆形类
public class Circle implements Shape {
    @Override
    public void draw() {
        System.out.println("Drawing a Circle");
    }
}

// 矩形类
public class Rectangle implements Shape {
    @Override
    public void draw() {
        System.out.println("Drawing a Rectangle");
    }
}


// 图形工厂
public class ShapeFactory {
    public static Shape getShape(String shapeType) {
        if (shapeType == null) {
            return null;
        }
        if (shapeType.equalsIgnoreCase("CIRCLE")) {
            return new Circle();
        } else if (shapeType.equalsIgnoreCase("RECTANGLE")) {
            return new Rectangle();
        }
        return null;
    }
}

客户端代码

public class Client {
    public static void main(String[] args) {
        Shape circle = ShapeFactory.getShape("CIRCLE");
        circle.draw(); // 输出:Drawing a Circle

        Shape rectangle = ShapeFactory.getShape("RECTANGLE");
        rectangle.draw(); // 输出:Drawing a Rectangle
    }
}
方法工厂
// 图形接口
public interface Shape {
    void draw();
}

// 圆形类
public class Circle implements Shape {
    @Override
    public void draw() {
        System.out.println("Drawing a Circle");
    }
}

// 矩形类
public class Rectangle implements Shape {
    @Override
    public void draw() {
        System.out.println("Drawing a Rectangle");
    }
}


// 抽象工厂类
public abstract class ShapeFactory {
    public abstract Shape createShape();
}

// 圆形工厂
public class CircleFactory extends ShapeFactory {
    @Override
    public Shape createShape() {
        return new Circle();
    }
}

// 矩形工厂
public class RectangleFactory extends ShapeFactory {
    @Override
    public Shape createShape() {
        return new Rectangle();
    }
}

客户端实现

public class Client {
    public static void main(String[] args) {
        ShapeFactory circleFactory = new CircleFactory();
        Shape circle = circleFactory.createShape();
        circle.draw(); // 输出:Drawing a Circle

        ShapeFactory rectangleFactory = new RectangleFactory();
        Shape rectangle = rectangleFactory.createShape();
        rectangle.draw(); // 输出:Drawing a Rectangle
    }
}
抽象工厂
// 图形接口
public interface Shape {
    void draw();
}
// 圆形类
public class Circle implements Shape {
    @Override
    public void draw() {
        System.out.println("Drawing a Circle");
    }
}

// 矩形类
public class Rectangle implements Shape {
    @Override
    public void draw() {
        System.out.println("Drawing a Rectangle");
    }
}
// 颜色接口
public interface Color {
    void fill();
}

// 红色类
public class Red implements Color {
    @Override
    public void fill() {
        System.out.println("Filling with Red color");
    }
}

// 蓝色类
public class Blue implements Color {
    @Override
    public void fill() {
        System.out.println("Filling with Blue color");
    }
}

// 抽象工厂类
public interface AbstractFactory {
    Shape createShape();
    Color createColor();
}

// 圆形工厂
public class CircleFactory implements AbstractFactory {
    @Override
    public Shape createShape() {
        return new Circle();
    }

    @Override
    public Color createColor() {
        return new Red(); // 默认返回红色
    }
}

// 矩形工厂
public class RectangleFactory implements AbstractFactory {
    @Override
    public Shape createShape() {
        return new Rectangle();
    }

    @Override
    public Color createColor() {
        return new Blue(); // 默认返回蓝色
    }
}

客户端实现

public class Client {
    public static void main(String[] args) {
        AbstractFactory circleFactory = new CircleFactory();
        Shape circle = circleFactory.createShape();
        Color red = circleFactory.createColor();

        circle.draw(); // 输出:Drawing a Circle
        red.fill();    // 输出:Filling with Red color

        AbstractFactory rectangleFactory = new RectangleFactory();
        Shape rectangle = rectangleFactory.createShape();
        Color blue = rectangleFactory.createColor();

        rectangle.draw(); // 输出:Drawing a Rectangle
        blue.fill();      // 输出:Filling with Blue color
    }
}

代理模式

静态代理的处理模式,在编译时就写死了,不足够灵活
JDK动态代理,靠接口实现(需要实现一些接口)
CGLIB动态代理,需要导入额外的包,

观察者模式

在这里插入图片描述

在这里插入图片描述
应用案例

  1. 事件监听
    在 GUI 应用程序中,按钮、文本框等组件通常使用观察者模式来处理用户事件。例如,按钮被点击时,所有注册的监听器都会被通知,执行相应的操作。
  2. 发布-订阅系统
    在消息推送系统中,观察者模式用于实现发布-订阅机制。发布者发布消息,所有订阅者收到通知并处理消息。例如,新闻网站发布新文章时,所有订阅用户都会收到通知。

策略模式

可以省掉很多的if-else

在这里插入图片描述

// 支付策略接口
public interface PaymentStrategy {
    void pay(int amount);
}
// 信用卡支付类
public class CreditCardPayment implements PaymentStrategy {
    private String cardNumber;

    public CreditCardPayment(String cardNumber) {
        this.cardNumber = cardNumber;
    }

    @Override
    public void pay(int amount) {
        System.out.println("Paid " + amount + " using Credit Card: " + cardNumber);
    }
}

// PayPal 支付类
public class PayPalPayment implements PaymentStrategy {
    private String email;

    public PayPalPayment(String email) {
        this.email = email;
    }

    @Override
    public void pay(int amount) {
        System.out.println("Paid " + amount + " using PayPal: " + email);
    }
}
// 上下文类
public class ShoppingCart {
    private PaymentStrategy paymentStrategy;

    public void setPaymentStrategy(PaymentStrategy paymentStrategy) {
        this.paymentStrategy = paymentStrategy;
    }

    public void checkout(int amount) {
        if (paymentStrategy == null) {
            System.out.println("Payment strategy not set!");
            return;
        }
        paymentStrategy.pay(amount);
    }
}
public class Client {
    public static void main(String[] args) {
        ShoppingCart cart = new ShoppingCart();

        // 使用信用卡支付
        cart.setPaymentStrategy(new CreditCardPayment("1234-5678-9012-3456"));
        cart.checkout(100); // 输出:Paid 100 using Credit Card: 1234-5678-9012-3456

        // 使用 PayPal 支付
        cart.setPaymentStrategy(new PayPalPayment("user@example.com"));
        cart.checkout(200); // 输出:Paid 200 using PayPal: user@example.com
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值