利用泛型实现一个Graph类
一、 定义一个接口Graph.java:
public
interface Graph<L> {
public static <L> Graph<L> empty() { } //其中这个方法需要具体实现 ###
public boolean add(L vertex);
public int set(L source, L target, int weight);
public boolean remove(L vertex);
public Set<L> vertices();
public Map<L, Integer> sources(L target);
public Map<L, Integer> targets(L source);
}
二、通过两种不同的类具体实现Graph
1、通过edge(记录关于边的信息,如起点、终点、权值)
定义一个Edge类
class Edge<L> {
private final L source_v;
private final L target_v;
private final int weight_e;
private final L target_v;
private final int weight_e;
}
再定义一个通过边来具体实现Graph的类ConcreteEdgesGraph
public class ConcreteEdgesGraph<L> implements Graph<L> {
//Field
private final Set<L> vertices = new HashSet<>();
private final List<Edge<L>> edges = new ArrayList<>();
//Constructor
public ConcreteEdgesGraph() {}
//Methods
@Override public boolean add(L vertex){}
@Override public int set(L source, L target, int weight){}
@Override public boolean remove(L vertex){}
@Override public Set<L> vertices(){}
@Override public Map<L, Integer> sources(L target){}
@Override public Map<L, Integer> targets(L source){}
}
2、通过vertex(记录关于点的信息,如这个点的名字,这个点连着哪些点,权值分别是什么)
同样,先定义一个Vertex类
class Vertex<L>{
public L name;
public Map<L , Integer> target = new HashMap<>();
public Map<L , Integer> target = new HashMap<>();
}
再通过具体的ConcreteVerticesGraph类来实现Graph
public class ConcreteVerticesGraph<L> implements Graph<L> {
//Field
private final List<Vertex<L>> vertices = new ArrayList<>();
//Constructor
public ConcreteVerticesGraph(){};
//Methods
@Override public boolean add(L vertex){}
@Override public int set(L source, L target, int weight){}
@Override public boolean remove(L vertex){}
@Override public Set<L> vertices(){}
@Override public Map<L, Integer> sources(L target){}
@Override public Map<L, Integer> targets(L source){}
}
于是,实现完所有的函数之后,可以再Graph接口中(###)调用
Graph<L> graph = new ConcreteEdgesGraph<L>();
或 Graph<L> graph = new ConcreteVerticesGraph<L>();
或 Graph<L> graph = new ConcreteVerticesGraph<L>();
这样就完整的实现了一个泛型接口,可以把“L”换成任意类型去使用,当然实现它并不是目的,最终的目的是利用已实现并封装好了的它,去更加方便快捷的处理问题。
使用方法等详情见后续博客