java设计模式:
1、单例模式
/* * 懒汉式单例模式 * 特点:在类加载时没有生成单例,只有当第一次调用getInstance时才会创建这个单例 * 缺点:使用了同步机制,影响性能。 * */ public class LazySingleton { private static volatile LazySingleton instance = null; //保证instance在所有线程中同步,volatile关键字保证了变量的可见性 private LazySingleton() { } //避免类在外部被实例化 public static synchronized LazySingleton getInstance() { if (instance == null) { instance = new LazySingleton(); } return instance; } }
/*饿汉式单例模式 特点:在类加载时就会创建单例,是线程安全的。 * */ public class HungrySingleton { private static final HungrySingleton instance=new HungrySingleton();//线程安全 private HungrySingleton(){} public static HungrySingleton getInstance(){ return instance; } }
2、工厂模式
public interface Product { void show(); } public class ConcreteProduct1 implements Product{ @Override public void show() { System.out.println("ConcreteProduct1 show"); } } public class ConcreteProduct2 implements Product{ @Override public void show() { System.out.println("ConcreteProduct2 show"); } } public interface AbstractFactory { Product createProduct(); } public class ConcreteFactory1 implements AbstractFactory{ @Override public Product createProduct() { return new ConcreteProduct1(); } } public class ConcreteFactory2 implements AbstractFactory{ @Override public Product createProduct() { return new ConcreteProduct2(); } } public class Test { public static void main(String[] args)throws Exception{ Class clazz=ConcreteFactory1.class; ConcreteFactory1 concreteFactory1=(ConcreteFactory1)clazz.newInstance(); ConcreteProduct1 concreteProduct1=(ConcreteProduct1) concreteFactory1.createProduct(); concreteProduct1.show(); } }
3、代理模式
public class DynamicProxy implements InvocationHandler { @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { System.out.println("before"); method.invoke(proxy,args); System.out.println("after"); return null; } }
4、迭代器模式
5、原型模式
/** * 原型模式 * 特点:用一个已经创建的实例作为原型,通过复制该原型对象创建一个和原型相同或者相似的新对象 */ public class Prototype implements Cloneable { public Prototype(){ System.out.println("创建成功"); } public Object clone() throws CloneNotSupportedException{ System.out.println("复制成功"); return (Prototype)super.clone(); } }