java—如果一个类不是另一个类的父类或子类,那么一个类如何调用另一个类的方法?

fkaflof6  于 2021-07-03  发布在  Java
关注(0)|答案(3)|浏览(370)

我正在阅读观察者模式设计,无法理解一个类如何调用另一个类的方法(一个不是另一个类的父/子方法)背后的逻辑。
例如,我有以下公司和雇员类。

public class Company {
    String  name;

    public void hire() {
        System.out.println("company hires employees");
    }
}

class Employee {
    int age;
    String  name;

    public void gotHired() {
        System.out.println("employee got hired by a company");
    }
}

这些类是否有可能采用彼此的方法进行通信。您可以添加任何有助于解释的方法。谢谢您

p4rjhz4m

p4rjhz4m1#

这是一个观察者实现。首先是界面:

public interface Observer
{
    public void notifyMe();
}

那么谁想得到通知:

public class Player implements Observer
{
    @Override public void notifyMe() {
        /* do something */
    }
}

public class Judge implements Observer
{
    @Override public void notifyMe() {
        /* do something */
    }
}

那么谁负责通知:

public class Game
{
    private ArrayList<Observer> listOfObserver;

    public Game() {
        listOfObserver = new ArrayList<>();
    }

    public void registerObserver(Observer observer) {
        listOfObserver.add(observer);
    }

    public void startGame() {
        ...
        ...
        ...

        /* when something important happens */
        for (int i = 0; i < listOfObserver.size(); i++)
            listOfObserver.notify();

        ...
        ...
        ...
    }
}

然后,这个 main() 功能:

public class Main
{
    public static void main(String args[]) {
        Player player1 = new Player();
        Player player2 = new Player();
        Player player3 = new Player();
        Player player4 = new Player();

        Judge judge = new Judge();

        Game game = new Game();
        game.registerObserver(player1);
        game.registerObserver(player2);
        game.registerObserver(player3);
        game.registerObserver(player4);
        game.registerObserver(judge);

        game.startGame();
    }
}
dfuffjeb

dfuffjeb2#

一个类应该包含另一个类对象的引用才能这样做

public class Company {
    String  name;
    Employee employee=new Employee();

    public void hire() {
        System.out.println("company hires employees");
    }
}

这样,company类对象就可以使用employee类方法
祝你好运!

piwo6bdm

piwo6bdm3#

对。他们可以交流。一个公司可以有几个员工,所以,

public class Company {
    String  name;
    List<Employee> empList = new ArrayList<Employee>();  // list of employees belonging to the company. "Composition" 

    public void hire() {
        System.out.println("company hires employees");
    }
    public void addEmployee(Employee e){ // add employee to company. I just got Hired!!!
    empList.add(e);
    }

    String getFirstEmployee(){ // get first employee
     if(!empList.isEmpty){
     Employee e = empList.get(0);
      return e
    }
   }

}

class Employee {
    int age;
    String  name;

    public void gotHired() {
        System.out.println("employee got hired by a company");
    }
}

相关问题