Dependence Inversion Principle (DIP) :

  1. Code design depends on abstract interfaces, not concrete implementations.

  2. Reduce coupling between classes through abstraction oriented programming for easy extension.

Examples of counter examples:

class LuckyDrawController {
  prizeRandom(users: User[], count: number): User[] {
    ...
  }

  prizeWeight(users: User[], count: number): User[] { ... }}Copy the code

UML class diagram:

Code implementation:

class User {
  name: string; / / user name
  level: number; // Membership level
  active: number; / / active value
  constructor(name: string, level: number, active: number) {
    this.name = name;
    this.level = level;
    this.active = active; }}Copy the code
Lottery interface: pass in all users who participate in the lottery and return the winners
interface ILuckyDraw {
  prize(users: User[], count: number): User[];
}
Copy the code
All random draw categories
class RandomLuckyDraw implements ILuckyDraw {
  prize(users: User[], count: number): User[] {
    / / shuffle
    const shuffleUsers = _.shuffle(users);
    // Randomly select three users
    return_.sampleSize(shuffleUsers, count); }}Copy the code
Abstract by weight
class WeightLuckyDraw implements ILuckyDraw {
  prize(users: User[], count: number): User[] {
    / / sorting
    const sortUsers = _.orderBy(users, ["level"."active"], ["desc"."desc"]);
    // Select the first three
    return_.take(sortUsers, count); }}Copy the code

Run example:

import { RandomLuckyDraw, WeightLuckyDraw, User } from "./DIP";

// Generate random users
let users = [];
for (let i = 0; i < 10; i++) {
  const user = new User(
    Mock.Random.cname(),
    Mock.Random.integer(0.10),
    Mock.Random.integer(50.100)); users.push(user); }// Random draw
const randomLuckyDraw = new RandomLuckyDraw();
const winners1 = randomLuckyDraw.prize(users, 3);
console.log(winners1);

// Weightdraw
const weightLuckyDraw = new WeightLuckyDraw();
const winners2 = weightLuckyDraw.prize(users, 3);
console.log(winners2);
Copy the code

[Online code] : Dependency inversion principle demonstration