Java: object oriented design; LinkedList and Stack

I am writing BFS and DFS in Java. What I was hoping to do was create a class like this:

/** Preforms BFS and DFS on ...
*/
public class Search{


  private XXX toSearch;
  // where XXX is an interface of Stack and LinkedList that has
  // remove() and add() methods.  

  public Search(boolean isBFS){
    if(isBFS)
      toSearch = new LinkedList();
    else
      toSearch = new Stack();
  }

  public void preformSearch(){
    while(toSearch.size() > 0){
      preformSearchOn(toSearch.remove());  // <----- KEY LINE
    }
  }

  private void preformSearchOn(...){...}

}

This class can execute BFS and DFS depending on how it is initialized. What is XXX? I do not think it exists.

I thought the whole point of object oriented programming could do such cool things.

What is the cleanest way to handle this?

+3
source share
4 answers

I think you are looking for a strategy template . The way to do this is not Java specific or other "cool stuff" on this subject. These types of things are transcend .

, BfsStrategy DfsStrategy. , . , , . ( /, , .)

:

public final class Seeker<E, K> {

    private final E structure;
    private final SearchStrategy strategy;

    public Seeker(final E aStructure, final SearchStrategy aStrategy) {
        structure = aStructure;
        strategy = aStrategy;
    }

    public boolean search(K aKey) {
        return strategy.search(structure, key); //Pretty generic.
    }

}
+11

, java.util.Iterator . ; JDK.

+1

XXX java.util.AbstractList, LinkedList, Stack .

, remove() . , : remove() pop(). remove() pop() java.util.Linkedlist (. Queue) java.util.Stack.

pop() remove() if, OO anti pateern. OO 3 :

  • BfsSearch: remove() .
  • DfsSearch: pop() .

, Search , BfsSearch DfsSearch.

OO . , , .

BTW OO, Larman:

UML : - (3- )

0

java.util.Queue.

As a queue with the first in the first you can use (for example) java.util.LinkedList or java.util.ArrayDeque .

As the last queue in the queue, you can wrap any Deque using java.util.Collections.asLifoQueue .

The stack, along with the Vector superscript vector, is deprecated because it synchronizes all access to the method, which is often not necessary. I suspect why it does not implement Queue.

0
source

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


All Articles