我正在阅读观察者模式设计,并且无法理解一个类如何调用另一个类的方法的方法背后的逻辑,哪个方法不是另一个类的父/子方法。
例如,我有以下公司和员工类。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");
}
}
这些课程是否有可能采用彼此的方法以便他们进行交流。您可以添加任何有助于解释的方法。 谢谢
答案 0 :(得分:2)
一个类应该包含其他类Object的引用才能这样做
public class Company {
String name;
Employee employee=new Employee();
public void hire() {
System.out.println("company hires employees");
}
}
通过这种方式,公司类对象可以使用Employee类方法
祝你好运!答案 1 :(得分:1)
是。他们可以沟通。一家公司可以有几个员工。所以,
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");
}
}
答案 2 :(得分:0)
这是观察者实施。首先是界面:
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();
}
}