Java 代码表示 UML 依赖/泛化/实现/关联/聚合/组合关系

Java UML About 1,806 words

依赖 - Dependence

/**
 * dependence: 依赖关系
 * UserService在类中用到了UserDao, User
 */
public class UserService {

    private UserDao userDao;

    //可以是构造,也可以用Spring注入
    public UserService(UserDao userDao) {
        this.userDao = userDao;
    }

    public void saveUser(User user) {
        userDao.save(user);
    }

}

public class UserDao {

    public void save(User user) {
        System.out.println("保存用户");
    }

}

public class User {
}

泛化 - Generalization

/**
 * Generalization: 泛化关系
 * 继承就是一种泛化
 * UserService继承了BaseService
 */
public class UserService extends BaseService {
}

public abstract class BaseService {
}

实现 - Implementation

/**
 * implementation: 实现关系
 * UserServiceImpl实现了UserService
 */
public class UserServiceImpl implements UserService {
}

public interface UserService {
}

关联 - Association

单向一对一关联

/**
 * association: 关联关系
 * 依赖关系的特例
 * 单向一对一关联
 * User关联IDCard
 */
public class User {
    private IDCard idCard;
}

public class IDCard {
}

双向一对一关联

/**
 * association: 关联关系
 * 依赖关系的特例
 * 双向一对一关联
 * User关联IDCard,IDCard中同样关联User
 */
public class User {
    private IDCard idCard;
}

public class IDCard {
    private User user;
}

聚合 - Aggregation

/**
 * aggregation: 聚合关系
 * 聚合关系是关联关系的特例
 * 整体和部分的关系,整体与部分可以分开
 * set方法设置Mouse、Keyboard
 */
public class Computer {

    private Mouse mouse;
    private Keyboard keyboard;

    public void setMouse(Mouse mouse) {
        this.mouse = mouse;
    }

    public void setKeyboard(Keyboard keyboard) {
        this.keyboard = keyboard;
    }
}

public class Mouse {
}

public class Keyboard {
}

组合 - Composition

/**
 * composition: 组合关系
 * 整体与部分的关系,但是整体与部分不可以分开
 * 直接new
 */
public class Computer {
    private Mouse mouse = new Mouse();
    private Keyboard keyboard = new Keyboard();
}

public class Mouse {
}

public class Keyboard {
}
Views: 5,004 · Posted: 2019-12-16

————        END        ————

Give me a Star, Thanks:)

https://github.com/fendoudebb/LiteNote

扫描下方二维码关注公众号和小程序↓↓↓

扫描下方二维码关注公众号和小程序↓↓↓


Today On History
Browsing Refresh