1. 组合模式
组合模式,将对象组合成树形结构以表示‘部分-整体’的层次结构。组合模式使得用户对单个对象和组合对象的使用具有一致性

public abstract class Component {
protected String name;
public Component(String name) {
this.name = name;
}
public abstract void add(Component c);
public abstract void remove(Component c);
public abstract void display(int depth);
}
public class Leaf extends Component {
public Leaf(String name) {
super(name);
}
@Override
public void add(Component c) {
System.out.println("不能加入新的节点");
}
@Override
public void remove(Component c) {
System.out.println("不能移除节点");
}
@Override
public void display(int depth) {
StringBuilder line = new StringBuilder();
for(int i = 0; i < depth; i++) {
line.append("-");
}
System.out.println(line.toString() + name);
}
}
import java.util.ArrayList;
public class Composite extends Component {
ArrayList<Component> CompositeList = new ArrayList<>();
public Composite(String name) {
super(name);
}
@Override
public void add(Component c) {
CompositeList.add(c);
}
@Override
public void remove(Component c) {
CompositeList.remove(c);
}
@Override
public void display(int depth) {
StringBuilder line = new StringBuilder();
for(int i = 0; i < depth; i++) {
line.append("-");
}
System.out.println(line.toString() + name);
for (Component c: CompositeList) {
c.display(depth + 2);
}
}
}
public class CompoenentClient {
public static void main(String[] args) {
Composite c = new Composite("ROOT");
c.add(new Leaf("LeafA"));
c.add(new Leaf("LeafB"));
Composite compositeA = new Composite("CompositeA");
c.add(compositeA);
compositeA.add(new Leaf("LeafC"));
c.display(1);
}
}
- 如果希望客户忽略组合对象和单个对象的不同,统一地使用组合结构中的所有对象时,就应该考虑使用组合模式了
2. 迭代器模式
迭代器模式,提供了一种方法顺序访问一个聚合对象中的各个元素,而又不暴露该对象的内部表示
- 当需要对聚集进行多种方式遍历时,可以用迭代器模式

3. 单例模式
保证一个类仅有一个实例,并提供访问它的一个全局访问点
public class single {
String name;
static single single_instance;
private single() {
this.name = "guanzihan";
}
public static single getSingle_instance() {
if(single_instance != null) {
single_instance =new single();
}
return single_instance;
}
}
3.1 多线程时的单例
public class single {
String name;
static single single_instance;
private static Object obj = new Object();
private single() {
this.name = "guanzihan";
}
public static single getSingle_instance() {
synchronized (obj) {
if(single_instance != null) {
single_instance =new single();
}
return single_instance;
}
}
}
3.2 静态初始化
- 静态初始化的方式是在自己被加载时就将自己实例化,所以被称为饿汉式单例类
- 单例模式是在第一次被引用时将自己实例化,所以被称为懒汉式单例类
网友评论