Suposse有一个“Worker”类,其中一个属性是“WorkOrder”对象的队列,另一个是“Boss”类,它是唯一可以添加或删除此队列的新“WorkOrders”的类。如何才能使修改队列的方法只能通过“Boss”访问?
我想到了两个解决方案:
(a)使方法包为private,将两个类保存在同一个包中,并在另一个包中实例化。
(b)使用“Worker”可以访问的方法建立接口,使该类的构造函数为private,并创建一个静态方法,该方法返回与接口类型相同的对象。
你有什么看法?你能想到一个更优雅的解决方案吗?答案 0 :(得分:1)
考虑使用一个接口来公开您想要公开的工作方法。老板可以持有对实现的引用(具有工作程序队列getter)并且仅将接口呈现给其他类。
import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Queue;
class Class {
public static void main(final String... args) {
final Boss boss = new Boss();
final Worker worker = boss.getWorker("sivmish");
worker.getWorkItems();//ERROR: only Boss has access to this.
}
}
interface Worker {
void processWork();
}
interface WorkOrder {
void doWork();
}
class WorkerImpl implements Worker {
private final Queue<WorkOrder> workItems;
WorkerImpl() {
this.workItems = new ArrayDeque<>();
}
public Queue<WorkOrder> getWorkItems() {
return workItems;
}
@Override
public void processWork() {
while (!workItems.isEmpty()) {
workItems.poll().doWork();
}
}
}
class Boss {
private final Map<String, WorkerImpl> workersByName;
Boss() {
workersByName = new HashMap<String, WorkerImpl>();
}
public Worker getWorker(final String name, WorkOrder... workOrders) {
if (!workersByName.containsKey(name)) {
final WorkerImpl worker = new WorkerImpl();
workersByName.put(name, worker);
}
final WorkerImpl worker = workersByName.get(name);
worker.getWorkItems().addAll(Arrays.asList(workOrders));
return worker;
}
}
答案 1 :(得分:0)
我宁愿建议将队列保留在Boss类中,因为你想让它只能被Boss访问才能添加或删除
class Boss
{
public LinkedList<E> queue = new LinkedList<E>();
private void add(item)
{
//do stuff...
}
private void remove()
{//do stuff...}
public static void viewOnly()
{
//display details
}
}
class Workers
{
public workers()
{
Boss.viewOnly();
}
}
class Main
{
public static void main(String args[])
{
Boss b = new Boss();
b.add(1); //job 1
b.add(5); //job 5
/* and so on..
*/
workers w = new workers();
}
}