开发者

Only allow some classes to call a method in Java

Lets say I have a structure like this:

Object A contains an instance of Object B

Object B contains an instance of Object C

Object D extends Object C

I have an instance of object D that other people will be writing and using in my program. There is some information about that object that I want to have but not give them access to though. What I am currently doing is storing that information and methods in Object B which cont开发者_运维技巧ains Object D instead of Object C.

The problem is if I make it private so that Object D can not use any of the methods, then I can not access them from anywhere else in the program either. Is there any way to make it so that D can not access a method but other classes can?


If I understood your problem correctly, you probably want to decouple an abstraction from implementation, so that you can change implementation in the future.

You can do that by implementing Bridge Design Pattern.

EDIT

To answer your comment:
You cannot call CircleShape's public method directly. DrawingAPI's concrete implementations (i.e. DrawingAPI1) should not have any idea about sheer existence of CircleShape class. If you somehow need to call some method of the caller, just define another interface and pass the reference of the caller to callee:

public interface CircleInfo {
  Color getBorderColor();
  /* some other methods */
}

public class CircleShape implements Shape, CircleInfo {
  public Color getBorderColor() {
    return Colors.Black; // not sure if it works, just an example
  }

  public void draw() {
    drawingAPI.drawCircle(x, y, radius, this);
  }   

  /* Other methods implementation here */
}

// DrawingAPI modification
interface DrawingAPI {
  public void drawCircle(double x, double y, double radius, CircleInfo info);
}

// Concrete implementation
class DrawingAPI1 implements DrawingAPI {
  public void drawCircle(double x, double y, double radius, CircleInfo info) {
    System.out.printf("API1.circle at %f:%f radius %f color %s\n",
      x, y, radius, info.getBorderColor().toString());
}


It sounds like D shouldn't extend C. An instance of D should instead have access to an instance that it can delegate to when needed. This delegate should be typed with an interface that you can have C implement. The interface will only include those methods D should be able to call. You inject an instance of this interface into D so it can do what it needs.

public interface Delegate {
    public String getInformation();
}

public class C implements Delegate {
    public String getInformation() {...}
    public void otherMethod();
    public void anotherOtherMethod();
}         

public class D {
    private Delegate delegate;

    public D(Delegate delegate) {
        this.delegate = delegate;
    }

    public void printSomething() {
        System.out.println(delegate.getInformation());
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜