Idiom for container classes

I was told to design the code according to the following code example:

Class Dogs{
   List<Dog> listOfDogs = new ArrayList<Dog>();
   // Setters, getters...
}

Class Dog{
   // Attributes and methods
}

The question arises: why is it better to implement the class Dogsas a container for ArrayList objects Dog, and not just refer to a simple ArrayList. Is encapsulation considered?

+4
source share
7 answers

Basically, creating a class Dogsprovides you with an extra layer of indirection.

, (.. ) Dogs, . , , , , , , ( Dogs - , ), .

. , "", , API Dogs. , Dogs . List.

" API" Visitor. Dogs visit(), . "", Dog, Dogs. .

+4

Dogs, Dogs , , . , releaseTheHounds() callEveryoneForDinner() ..

, , , List listOfDogs, ArrayList. , :

List listOfDogs = new ArrayList<Dog>();

:

ArrayList listOfDogs = new ArrayList<Dog>();

, . "" ArrayList List. (, TreeList), , listOfDogs.

, : :

List<Dog> listOfDogs = new ArrayList<Dog>();

, List Dog .

+4

, - , , , . .

, Dog, , , . , , / . , Dogs. , , , .. , .

Class Dogs
{
  List listofDogs = new ArrayList<Dog>();

  public void AddDog(Dog newDog)
  {
     //check if valid
  }

  public List<Dog> getDogs()
  {
    //return readonly dogs collection
  }
}
+4

- mvc,

+1

, . , ArrayList , , , desc.

+1

, , , , - " ". - , , . , , .

, Dog - PooledObject, , PooledObject, .

0

​​, , . , . , , , , : push, remove, , .., Dog Object; .

, Dog, .

0

Source: https://habr.com/ru/post/1540374/


All Articles