JAVA架构师之路一:七大软件设计原则

本文详细介绍了JAVA架构师必须掌握的七大软件设计原则:开闭原则、依赖倒置原则、单一职责原则、接口隔离原则、迪米特法则、里氏替换原则和合成复用原则,阐述了每个原则的定义、优点,并通过代码示例进行说明,旨在提升代码的可维护性和可扩展性。
摘要由CSDN通过智能技术生成

矩不正,不可为方;规不正,不可为圆.——淮南子

任何行业或者圈子都有自己的规则,遵从规则是在这个行业立足的根本,不然你就会被这个行业淘汰。软件设计同样有自己的原则。遵循这样的原则,你的代码软件才能更容易被接受,才会使你更专业。

1. 开闭原则

定义

一个软件实体如类、模块和函数应该对扩展开放,对修改关闭。
用抽象构建框架,用实现扩展细节。

优点

提高软件的可复用性及可维护性

代码

/**
 * The interface Boo k.
 */
public interface Book {
   

    /**
     * Gets id.
     *
     * @return the id
     */
    Integer getId();

    /**
     * Gets name.
     *
     * @return the name
     */
    String getName();

    /**
     * Gets price.
     *
     * @return the price
     */
    Double getPrice();
}
/**
 * The type Java book.
 */
public class JavaBook implements Book {
   

    private Integer id;

    private String name;

    private Double price;

    /**
     * Instantiates a new Java book.
     *
     * @param id    the id
     * @param name  the name
     * @param price the price
     */
    public JavaBook(Integer id, String name, Double price) {
   
        this.id = id;
        this.name = name;
        this.price = price;
    }

    /**
     * Sets id.
     *
     * @param id the id
     */
    public void setId(Integer id) {
   
        this.id = id;
    }

    /**
     * Sets name.
     *
     * @param name the name
     */
    public void setName(String name) {
   
        this.name = name;
    }

    /**
     * Sets price.
     *
     * @param price the price
     */
    public void setPrice(Double price) {
   
        this.price = price;
    }

    @Override
    public Integer getId() {
   
        return this.id;
    }

    @Override
    public String getName() {
   
        return this.name;
    }

    @Override
    public Double getPrice() {
   
        return this.price;
    }
/**
 * The type Discount java book.
 */
public class DiscountJavaBook extends JavaBook {
   
    /**
     * Instantiates a new Java book.
     *
     * @param id    the id
     * @param name  the name
     * @param price the price
     */
    public DiscountJavaBook(Integer id, String name, Double price) {
   
        super(id, name, price);
    }

    @Override
    public Double getPrice() {
   
        return super.getPrice() * 0.5;
    }
}
public class Test {
   

    public static void main(String[] args) {
   
        Book book = new JavaBook(1, "《Java开发指南》", 79.9);
        System.out.println("书本Id: " + book.getId() +
                "\n书本名字: " + book.getName() +
                "\n书本售价: " + book.
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值