创建型模式

来源:互联网 发布:java的引用类型 编辑:程序博客网 时间:2024/05/16 04:36

参考:http://blog.csdn.net/jason0539
  整理如下:(本文适合对oop编程熟悉并且了解设计模式的朋友
综述_me:
1.设计模式封装的是业务流程中能大致定量其变化,扩展的量的部分;
2.80%的时候设计模式封装的是多重判断;
3.用到了接口,多态;
4.设计模式的思想不仅存在于代码的构建中(如JAVA语言中,SSH,SSI框架中等等),甚至某些公司就是宏观的设计模式的体现。

统一说明:23中设计模式很多十分相像,区分点在于他们的侧重点不一样!

设计模式分为三大类:
  创建型模式,共五种:单例模式、工厂方法模式、抽象工厂模式、建造者模式、原型模式。
  
单例模式:
单利模式一般分为两种:

1.懒汉式:

public class Singleton {      //私有的默认构造子      private Singleton() {}      //初始化为null        private static Singleton single=null;    //锁      public static Object ob = new Object();    //静态工厂方法       public static  Singleton getInstance() {          if (single == null)             synchronized(ob)            {                    single = new Singleton();               }            return single;      }  }  

2.饿汉式

public class Singleton{    //私有化默认构造(必须的)    private Singleton(){}    //初始化好    private static Singleton singleton=new Singleton();    //创建构造方法     public static Singleton getInstance()    {         return singleton;    }}

注意点:
1)通过Java反射机制是能够实例化构造方法为private的类的。
2)在计算机系统中,线程池、缓存、日志对象、对话框、打印机、显卡的驱动程序对象常被设计成单例。

工厂模式:

工厂模式分简单工厂模式、工厂方法模式、抽象工厂模式

最开始的时候客户需要创建某个商品的时候需要自己手动去创建(new的方式);
code:
客户端:

public class Client{    public static void main(String []args)    {        Car car =new Car();        Knife knife=new Knife();    }}

  随着客户需求的产品种类的增多,交由手动的创建的方式,生产效率太低,不利于提高社会生产力,于是诞生了简单工厂模式。简单工厂模式把每个类的创建都交给一个工厂类去创建。这种类掌管着产品的创建(创造),我们称作为全能或者上帝类。
简单工厂模式
code:

//产品类:public class Product {    public Product(){}}public class ProductA extends Product{     public ProductA()    {        System.out.println("Create ProductA......");    }}public class ProductB extends Product{     public ProductB()    {        System.out.println("Create ProductA......");    }}//工厂类:public class Factory{    public static Map<String,Product> productManager=new HashMap<String,Product>();    public Factory()    {        //通过读取配置文件加载各个产品类        productManager=......;    }    public static Product createProduct(String productName)    {        return productManager.get(productName);    }}//客户端public class Customer {     public static void main(String []args)    {        Factory factory=new Factory();        Product ProductA=factory.createProduct("ProductA");        Product ProductB=factory.createProduct("ProductB");    }}

  随着业务的扩展,产品创建过程的复杂度增加(各种商业逻辑判断,权限判断,验证等等),当新增加一个产品的时候,使用简单工厂模式的时候需要修改代码,而这不符合“开闭原则”。由于是创建产品的方法里面增加了复杂的业务逻辑导致了原先模式的不灵活,此时,工厂方法模式应运而生。工厂方法模式去掉了简单工厂模式中工厂方法的静态属性,使得它可以被子类继承。这样在简单工厂模式里集中在工厂方法上的压力可以由工厂方法模式里不同的工厂子类来分担。
工厂方法模式
code:

//产品类:public class Product{       public Product(){}}public class ProductA extends Product{    public ProductA()    {        System.out.println("Create ProductA......");    }}public class ProductB extends Product{    public ProductB()    {        System.out.println("Create ProductA......");    }}//工厂类:public interface Factory{    Product createProduct();}public FactoryA implements Factory{    @Override     ProductA createProduct()    {         //复杂的业务逻辑判断        if(getSession().get("Authorty")=="Admin")        {                return new ProductA();        }        return null;     }   }public FactoryB implements Factory{    @Override     ProductB createProduct()    {         //复杂的业务逻辑判断         if(getSession().get("state")=="pass")         {             return new ProductB();         }         return null;     }  }//客户端:public class Customer {    public static void main(String []args)    {      Factory factoryA=new FactoryA();      Product ProductA=factoryA.createProduct();      Factory factoryB=new FactoryB();    Product ProductA=factoryB.createProduct();    }}

  随着业务复杂度继续的增加,由于产品种类的增加,产品工厂的实例会变得很多。然而很多产品可以归类,有些产品属于一个产品簇。例如,手机配套的产品有充电宝,数据线等等,具体一点的:苹果手机的配件有苹果充电宝,苹果耳机,苹果数据线等等。为了适应这种变化,抽象工厂模式应运而生。
抽象工厂模式
code:

//产品类abstract class ProductUSB{    void productUSB();}public class ProductUSB4Iphone extends ProductUSB{    public productUSB()    {        System.out.println("CreateProductUSB4Iphone......");    }}public class ProductUSB4Xiaomi extends ProductUSB{    public productUSB()    {        System.out.println("Create ProductUSB4Xiaomi......");    } }abstract class Source{    void source();}public class SourceIphone extends Source{    public void source()    {        System.out.println("create SourceIphone......");    }}public class SourceXiaomi extends Source{    public source()    {        System.out.println("create SourceXiaomi......")    }}//工厂类abstract class Factory{    ProductUSB createUSB();    Source createSource();}public class FactoryIphone extends Factory{    @Override     public ProductUSBIphone createUSB()    {        return new ProductUSBIphone();    }    @Override     public SourceIphone createSource()    {        return new SourceIphone();    }}public class FactoryXiaomi extends Factory{    @Override     public ProductUSBXiaomi createUSB()    {        return new ProductUSBXiaomi();    }    @Override     public SourceXiaomi createSource()    {        return new SourceXiaomi();    }}//客户端public class Client{    public static void main(String []args)    {        //create Iphone        Factory factoryIphone=new FactoryIphone();        ProductUSB4Iphone puIphone=factoryIphone.createUSB();        SourceIphone siph=factoryIphone.createSource();        //create XiaomiFactory factoryXiaomi=new FactoryXiaomi();        ProductUSBXiaomi peXiaomi=factoryXiaomi.creaeUSB();        SourceXiaomi sx=factoryXiaomi.createSource();    }}

原型模式:
  实现clonable接口,重写clone方法,之所以重写clone方法,是因为Object类中clone方法其作用域是protected类型的,一般的类无法调用(只有同包下通过调用Object.clone()或者继承的类中this.clone()才可以访问,继承的类在外部实例化后不能访问protected修饰的方法(只能在内部访问)!),因此,Prototype类需要将clone方法的作用域修改为public类型并且使用super.clone()去具体实现;
之所以使用super.clone()而不用this.clone(),是为了避免调用者出现无限递归的bug。
对于复杂的耗时的创建对象过程(可以用Thread.sleep(long time)去模拟),此种方式比new 的方式效率高很多。

package DesignMode.prototype;public class Prototype implements Cloneable{    public Prototype()    {        try        {            Thread.sleep(1);        }        catch (InterruptedException e)        {            e.printStackTrace();        }    }    @Override    public Prototype clone()    {        Prototype prototype = null;        try        {            prototype = (Prototype)super.clone();        }        catch (CloneNotSupportedException e)        {            e.printStackTrace();        }        return prototype;    }    public void show()    {        Object o = new Object();        System.out.println("Prototype.show()"+o.toString());    }    public static void main(String[] args)    {        System.out.println("...................创建对象的方式对比..............................");        Prototype prototype = new Prototype();        prototype.show();        System.out.println("-----------------------------------");        Prototype prototypeCopy = (Prototype)prototype.clone();        prototypeCopy.show();        System.out.println("...................两种创建方式效率对比.............................");              //new Style         long start = 0, end = 0;        Prototype prototypeNew = null;        start = System.currentTimeMillis();        for (int i = 0; i < 10000; i++ )        {            prototypeNew = new Prototype();        }        end = System.currentTimeMillis();        System.out.println("The new Style cost time : " + (end - start));        //Clone Style        Prototype prototypeCop = new Prototype();        Prototype prototypeShow = null;        start = System.currentTimeMillis();        for (int i = 0; i < 10000; i++ )        {            prototypeShow = prototypeCop.clone();        }        end = System.currentTimeMillis();        System.out.println("The Clone style cost time : " + (end - start));    }}

建造者模式:
  当同一个类型的对象创建的过程(需要初始化的内容或者数量)不一样的时候,将对象的创建过程使用Builder,Director,Product的模式封装。让获取对象的过程与对象创建的多种实现分开扩展。
适用情形:
1、当创建复杂对象的算法应该独立于该对象的组成部分以及它们的装配方式时。
2、当构造过程必须允许被构造的对象有不同表示时。

package DesignMode.build;// Productclass Conn{    String dataSources = "";// 简单起见省略get/set方法    @Override    public String toString()    {        return "my dataSources is : " + dataSources;    }}// 建造者接口interface Builder{    void getSource();    Conn returnConn();}// Sql建造者实现class SqlBuilder implements Builder{    Conn conn = new Conn();    @Override    public void getSource()    {        this.conn.dataSources = "Many SQLDataSources";    }    @Override    public Conn returnConn()    {        return conn;    }}// Oracle建造者实现class OracleBuilder implements Builder{    Conn conn = new Conn();    @Override    public void getSource()    {        this.conn.dataSources = "One OracleDataSources";    }    @Override    public Conn returnConn()    {        return conn;    }}// 导演类class Director{    Builder builder;    public Director(Builder builder)    {        this.builder = builder;        builder.getSource();    }    public Conn ReceiveSources()    {        return builder.returnConn();    }}// Testpublic class MyBuilderMode{    public static void main(String[] args)    {        Director sqlDirector = new Director(new SqlBuilder());        Conn sqlConn = sqlDirector.ReceiveSources();        System.out.println(sqlConn);        System.out.println("---------------------------------");        Director oracleDirector = new Director(new OracleBuilder());        Conn OracleConn = oracleDirector.ReceiveSources();        System.out.println(OracleConn);    }}
0 0
原创粉丝点击