引用传递实际应用

Posted on 2020-08-18  224 Views


类关联结构

class Human {
  private String name;
  private int age;
  private car car; // 一个人有一辆车

  public Human(String name, int age) {
    this.name = name;
    this.age = age;
  }

  public void setCar(car car) {
    this.car = car;
  }

  public car getCar() {
    return car;
  }

  public String getInfo() {
    return "姓名:" + this.name + "年龄:" + this.age;
  }
}

class car {
  private String name;
  private double price;
  private Human human; // 车应该属于一个人

  public car(String name, double price) {
    this.name = name;
    this.price = price;
  }

  public void setHuman(Human human) {
    this.human = human;
  }

  public Human getHuman() {
    return this.human;
  }

  public String getInfo() {
    return "汽车品牌" + this.name + "汽车价格" + this.price;
  }
}

public class HumanDemo {
  public static void main(String[] args) {
    Human human = new Human("张三", 20);
    car car = new car("宾利", 8000000.00);
    human.setCar(car); // 一个人有一辆车
    car.setHuman(human); // 车应该属于一个人
    System.out.println(human.getCar().getInfo());
    System.out.println(car.getHuman().getInfo());
  }
}

自身关联

public class ChildDemo {
  public static void main(String[] args) {
    Human adult = new Human("张三", 20);
    Human childA = new Human("李四", 21);
    Human childB = new Human("王五", 22);
    childA.setCar(new car("吉利", 50000));
    childB.setCar(new car("大众", 60000));
    adult.setChild(new Human[] {childA, childB});
    for (int i = 0; i < adult.getChild().length; i++) {
      System.out.println(adult.getChild()[i].getInfo());
      System.out.println(adult.getChild()[i].getCar().getInfo());
    }
  }
}

合成设计模式

class Computer {
  private Display display[];
  private Host host;
}

class Host {
  private Keyboard keyboard;
  private Mouse mouse;
} // 主机

class Mainboard {
  private Memory memory[];
  private Cpu cpu;
  private Gpu gpu;
  private Disk disk[];
} // 主板

class Keyboard {} // 键盘

class Mouse {} // 鼠标

class Memory {} // 内存

class Cpu {} // CPU

class Gpu {} // 显卡

class Disk {} // 硬盘

class Display {} // 显示器