OOP - How this relationship could be done in Object-Oriented Programming

108 views Asked by At

Suppose there is a class A and it has many instances from class B, and in A, it will have some shared attributes for B to access. Simply I can write this type, I just want to know if there are any pattern or some other good way to make this relationship in OOP.

My idea is straightforward :

class A {
      protected int shared;
      public List<B> bList;

      int getShared ()
      {
          return shared;
      }

}

class B {
      protected A _a;

      B (A a) {
            this._a = a;
      }

      void hello () {
            print (this._a.getShared()); 
      }
}

As I am pretty much a novice in OOP, so I think maybe there some pattern can do this better, looking forward your ideas. Thanks.

1

There are 1 answers

1
Alexander Yancharuk On BEST ANSWER

Your code is looking like Mediator pattern. Except that classically Mediator (A class) has a set of different objects for interacting with or between them without explicit references.