Java设计模式--笔记

一.几种常用设计模式

1.单例设计模式

单例设计模式永远只会有一个实例化对象生产。实现步骤:私有化构造方法,提供一个公共的方法获取该实例对象。

示例(多种实现方式):

/**  
 *   
 * 饿汉式,线程安全 但效率比较低  
 */  
public class Singleton {   
  
    private Singleton() {   
    }   
  
    private static final Singleton instance = new Singleton();   
  
    public static Singleton getInstance() {   
        return instance;   
    }   
  
}  
/**  
 * 饱汉式,线程不安全   
 *   
 */  
public class Singleton {   

    private Singleton() {   
    }   
  
    private static Singleton instance;   
  
    public static Singleton getInstance() {   
        if (instance == null)   
            instance = new Singleton();   
        return instance;   
    }   
}  
/**  
 * 使用synchronized修饰方法,线程安全,效率低  
 *  
 */  
public class Singleton { 
      
    private Singleton() {   
    }   
  
    private static Singleton instance;   
  
    public static synchronized Singleton getInstance() {   
        if (instance == null)   
            instance = new Singleton();   
        return instance;   
    }   
}  
/**  
 * 使用同步代码块,同步方法的优化,线程安全,效率较高 
 *  
 */  
public class Singleton {  
 
    private static Singleton instance;   
  
    private Singleton() {   
    }   
  
    public static Singleton getIstance() {   
        if (instance == null) {   
            synchronized (Singleton.class) {   
                if (instance == null) {   
                    instance = new Singleton();   
                }   
            }   
        }   
        return instance;   
    }   
}  

2.工厂设计模式

定义一个创建对象的接口,让子类决定实例化那个类。示例:

interface Animal {
    public void say(); 
}   
  
class Cat implements Animal {

    @Override  
    public void say() { 
        System.out.println("喵喵喵!");   
    }   
}   
  
class Dog implements Animal { 
  
    @Override  
    public void say() { 
        System.out.println("汪汪汪!");   
    }   
}   
  

  
/**
*  简单工厂
*
*/  
class SimpleFactory { 

    public static Animal getInstance(String className) {   
        Animal animal = null;   
        if ("Cat".equals(className)) { 
            animal = new Cat(); 
        }   
        if ("Dog".equals(className)) { 
            animal = new Dog(); 
        }   
        return animal ;   
    }   

}   
/**
 * 简单工厂放射实现
 *
 */
public class SampleFactory1 {
    public static Animal getInstance(Class c){
        Animal animal= null;
        try {
            animal= (Animal ) Class.forName(c.getName()).newInstance();
        } catch (InstantiationException e) {
            System.out.println("不支持抽象类或接口");
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            // TODO Auto-generated catch block
            System.out.println("没有足够权限,即不能访问私有对象");
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            System.out.println("类不存在");
            e.printStackTrace();
        }    
        return animal;
    }
}

3.代理设计模式

为其他对象提供一个代理以便控制这个对象的访问。示例:


public interface Phone{
    void createPhone();
}

/**
 *  目标对象实现了某一接口
 */
public class Iphone implements Phone{

    public void createPhone(){
        System.out.println("生产iphone");

    }  
}

/**
 *  静态代理
 */
public class PhoneProxy implements Phone{

    private Phone phone;

    public PhoneProxy (Phone phone){
        this.phone=phone;
    }
    // 
    public void createPhone() {
        System.out.println("开始生产phone")
        phone.createPhone();
    }
}

/**
 * 测试类
 */
public class Test {
    public static void main(String[] args) {
        //目标对象
        Phone phone = new Phone();
        //代理对象
        Phone phoneProxy = new PhoneProxy(phone );
        //执行的是代理的方法
        phoneProxy.createPhone();
    }
}
/**
* 动态代理
*
*
*/
public class DynamicProxy implements InvocationHandler {
    private Object object;
    public DynamicProxy(Object object) {
        this.object = object;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        Object result = method.invoke(object, args);
        return result;
    }
}

public class Test{
    public static void main(String[] args) {
        Iphone iphone= new Iphone();
        DynamicProxy proxy = new DynamicProxy(iphone);
        ClassLoader classLoader = iphone.getClass().getClassLoader();
        Phone phone= (Phone ) Proxy.newProxyInstance(classLoader, new  Class[]{Phone .class}, proxy);
        phone.createPhone();
    }
}

创建动态代理的对象,需要借助Proxy.newProxyInstance。该方法的三个参数分别是:

  • ClassLoader loader表示当前使用到的appClassloader。
  • Class<?>[] interfaces表示目标对象实现的一组接口。
  • InvocationHandler h表示当前的InvocationHandler实现实例对象。

4.观察者设计模式

所谓观察者模式,举个例子现在许多购房者都密切观察者房价的变化,当房价变化时,所有购房者都能观察到,以上的购房者属于观察者,这便是观察者模式。示例:

/**
*    java提供Obeservable类和Observer
*
**/
class House extends Observable {   

    private float price;   
  
    public void setPrice(float price) {   
        this.setChanged();// 设置变化点  
        this.notifyObservers(price);// 通知所有观察者价格改变  
        this.price = price;   
    }   
  
    public float getPrice() {   
        return this.price;   
    }   
  
    public House(float price) {   
        this.price = price;   
    }   
  
    public String toString() {   
        return "房子价格为: " + this.price;   
    }   
}   
  
class HousePriceObserver implements Observer {   

    private String name;   
  
    public HousePriceObserver(String name) {   
        super();   
        this.name = name;   
    }   
  
    @Override  
    public void update(Observable o, Object arg) {// 只要改变了 observable 对象就调用此方法  
        if (arg instanceof Float) {   
            System.out.println(this.name + "观察的价格更改为:"  
                    + ((Float) arg).floatValue());   
        }   
  
    }   
  
}   
  
public class ObserDeom {   
    public static void main(String[] args) {   
        House h = new House(1000000);   
        HousePriceObserver hpo1 = new HousePriceObserver("购房者A");   
        HousePriceObserver hpo2 = new HousePriceObserver("购房者B");   
        HousePriceObserver hpo3 = new HousePriceObserver("购房者C");   
        h.addObserver(hpo1);// 给房子注册观察者   
        h.addObserver(hpo2);// 给房子注册观察者   
        h.addObserver(hpo3);// 给房子注册观察者   
        System.out.println(h);// 输出房子价格   
        // 修改房子价格,会触发update(Observable o, Object arg)方法通知购房者新的房价信息  
        h.setPrice(2222222);//   
        System.out.println(h);// 再次输出房子价格   
    }   
}  

 

猜你喜欢

转载自blog.csdn.net/luhong327/article/details/87345161