创建型设计模式

1.abstract   factory

抽象工厂模式,以抽象工厂为核心。创建多个不相干的产品,一个抽象工厂,一个具体工厂,都包含创建多个产品的方法

//抽象工厂类
public abstract class AbstractFactory {
    public abstract Vehicle createVehicle();
    public abstract Weapon createWeapon();
    public abstract Food createFood();
}
//具体工厂类,其中Food,Vehicle,Weapon是抽象类,
public class DefaultFactory extends AbstractFactory{
    @Override
    public Food createFood() {
        return new Apple();
    }
    @Override
    public Vehicle createVehicle() {
        return new Car();
    }
    @Override
    public Weapon createWeapon() {
        return new AK47();
    }
}
//测试类
public class Test {
    public static void main(String[] args) {
        AbstractFactory f = new DefaultFactory();
        Vehicle v = f.createVehicle();
        v.run();
        Weapon w = f.createWeapon();
        w.shoot();
        Food a = f.createFood();
        a.printName();
    }
}

2.build

生成器模式,创建复杂对象,指导者和建造者(可以分抽象,具体)

  1. public interface PersonBuilder {  
  2.      void buildHead();  
  3.      void buildBody();  
  4.      void buildFoot();  
  5.      Person buildPerson();  
  6. }  

  1. public class ManBuilder implements PersonBuilder {  
  2.      Person person;  
  3.      public ManBuilder() {  
  4.           person = new Man();  
  5.      }  
  6.      public void buildbody() {  
  7.           person.setBody("建造男人的身体");  
  8.      }  
  9.      public void buildFoot() {  
  10.           person.setFoot("建造男人的脚");  
  11.      }  
  12.      public void buildHead() {  
  13.           person.setHead("建造男人的头");  
  14.      }  
  15.      public Person buildPerson() {  
  16.           return person;  
  17.      }  
  18. }  

  1. public class WomanBuilder implements PersonBuilder {  
  2.      Person person;  
  3.      public WomanBuilder() {  
  4.           person = new Woman();  
  5.      }  
  6.      public void buildbody() {  
  7.           person.setBody(“建造女人的身体");  
  8.      }  
  9.      public void buildFoot() {  
  10.           person.setFoot(“建造女人的脚");  
  11.      }  
  12.      public void buildHead() {  
  13.           person.setHead(“建造女人的头");  
  14.      }  
  15.      public Person buildPerson() {  
  16.           return person;  
  17.      }  
  18. }  

  1. public class PersonDirector {  
  2.      public Person constructPerson(PersonBuilder pb) {  
  3.           pb.buildHead();  
  4.           pb.buildBody();  
  5.           pb.buildFoot();  
  6.           return pb.buildPerson();  
  7.      }  
  8. }  

  1. public class Person {  
  2.      private String head;  
  3.      private String body;  
  4.      private String foot;  
  5.   
  6.      public String getHead() {  
  7.           return head;  
  8.      }  
  9.      public void setHead(String head) {  
  10.           this.head = head;  
  11.      }  
  12.      public String getBody() {  
  13.           return body;  
  14.      }  
  15.      public void setBody(String body) {  
  16.           this.body = body;  
  17.      }  
  18.      public String getFoot() {  
  19.           return foot;  
  20.      }  
  21.      public void setFoot(String foot) {  
  22.           this.foot = foot;  
  23.      }  
  24. }  
  25. public class Man extends Person {  
  26.      public Man(){  
  27.           System.out.println(“开始建造男人");  
  28.      }  
  29. }  
  30. public class Woman extends Person {  
  31.      public Woman(){  
  32.           System.out.println(“开始建造女人");  
  33.      }  
  34. }  

  1. public class Test{  
  2.      public static void main(String[] args) {  
  3.           PersonDirector pd = new PersonDirector();  
  4.           Person womanPerson = pd.constructPerson(new ManBuilder());  
  5.           Person manPerson = pd.constructPerson(new WomanBuilder());  
  6.      }  
  7. }  

android,

  public class UserBean {
    public int age;
    public String name;
    public float bodyWeight;
    public float height;
    public int likeCount;
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public float getBodyWeight() {
        return bodyWeight;
    }
    public void setBodyWeight(float bodyWeight) {
        this.bodyWeight = bodyWeight;
    }
    public float getHeight() {
        return height;
    }
    public void setHeight(float height) {
        this.height = height;
    }
    public int getLikeCount() {
        return likeCount;
    }
    public void setLikeCount(int likeCount) {
        this.likeCount = likeCount;
    }
    public static class Builder {
        UserBean userBean;
        public Builder() {
            this.userBean = new UserBean();
        }
        public Builder setName(String name) {
            this.userBean.setName(name);
            return this;
        }
        public Builder setAge(int age) {
            this.userBean.setAge(age);
            return this;
        }
        public Builder setBodyWeight(float bodyWeight) {
            this.userBean.setBodyWeight(bodyWeight);
            return this;
        }
        public Builder setHeight(float height) {
            this.userBean.setHeight(height);
            return this;
        }
        public UserBean build() {
            return this.userBean;
        }
    }
}
UserBean userBean = new UserBean.Builder().setAge(18)
            .setName("Bernie")
            .setHeight((float) 175.0)
            .setBodyWeight((float) 80.0)
            .build();

3.factory    method

工厂方法模式,一个抽象工厂,多个具体工厂,一个抽象产品,多个具体产品。具体工厂分别创建对应的具体产品

//抽象产品角色
public interface Moveable {
    void run();
}
//具体产品角色
public class Plane implements Moveable {
    @Override
    public void run() {
        System.out.println("plane....");
    }
}

public class Broom implements Moveable {
    @Override
    public void run() {
        System.out.println("broom.....");
    }
}

//抽象工厂
public abstract class VehicleFactory {
    abstract Moveable create();
}
//具体工厂
public class PlaneFactory extends VehicleFactory{
    public Moveable create() {
        return new Plane();
    }
}
public class BroomFactory extends VehicleFactory{
    public Moveable create() {
        return new Broom();
    }
}
//测试类
public class Test {
    public static void main(String[] args) {
        VehicleFactory factory = new BroomFactory();
        Moveable m = factory.create();
        m.run();
    }
}

4.prototype

原型模式,创建一样的,区分浅拷贝(共享内存)和深拷贝(独立内存)

// Prototype pattern -- Structural example  
using System;

// "Prototype"
abstract class Prototype
{
  // Fields
  private string id;

  // Constructors
  public Prototype( string id )
  {
    this.id = id;
  }


  public string Id
  {
    getreturn id; }
  }


  // Methods
  abstract public Prototype Clone();
}


// "ConcretePrototype1"
class ConcretePrototype1 : Prototype
{
  // Constructors
  public ConcretePrototype1( string id ) : base ( id ) {}

  // Methods
  override public Prototype Clone()
  {
    // Shallow copy
    return (Prototype)this.MemberwiseClone();
  }

}


// "ConcretePrototype2"
class ConcretePrototype2 : Prototype
{
  // Constructors
  public ConcretePrototype2( string id ) : base ( id ) {}

  // Methods
  override public Prototype Clone()
  {
    // Shallow copy
    return (Prototype)this.MemberwiseClone();
  }

}


/// <summary>
/// Client test
/// </summary>

class Client
{
  public static void Main( string[] args )
  {
    // Create two instances and clone each
    ConcretePrototype1 p1 = new ConcretePrototype1( "I" );
    ConcretePrototype1 c1 = (ConcretePrototype1)p1.Clone();
    Console.WriteLine( "Cloned: {0}", c1.Id );

    ConcretePrototype2 p2 = new ConcretePrototype2( "II" );
    ConcretePrototype2 c2 = (ConcretePrototype2)p2.Clone();
    Console.WriteLine( "Cloned: {0}", c2.Id );
  }

}

5.singleton

单体模式,考虑并发,很少考虑反射。构造方法私有,静态内部类获取

  1. public class Singleton {  
  2.     private Singleton() {}  
  3.     private static Singleton single=null;  
  4.  
  5.     public static Singleton getInstance() {  
  6.          if (single == null) {    
  7.              single = new Singleton();  
  8.          }    
  9.         return single;  
  10.     }  
  11. }  

  1. 比较慢,每次都同步
  1. public static synchronized Singleton getInstance() {  
  2.          if (single == null) {    
  3.              single = new Singleton();  
  4.          }    
  5.         return single;  
  6. }  

volatile关键字来声明单例对象
  1. public static Singleton getInstance() {  
  2.         if (singleton == null) {    
  3.             synchronized (Singleton.class) {    
  4.                if (singleton == null) {    
  5.                   singleton = new Singleton();   
  6.                }    
  7.             }    
  8.         }    
  9.         return singleton;   
  10.     }  

比较好

  1. public class Singleton {    
  2.     private static class LazyHolder {    
  3.        private static final Singleton INSTANCE = new Singleton();    
  4.     }    
  5.     private Singleton (){}    
  6.     public static final Singleton getInstance() {    
  7.        return LazyHolder.INSTANCE;    
  8.     }    
  9. }    

占着内存,快

  1. public class Singleton1 {  
  2.     private Singleton1() {}  
  3.     private static final Singleton1 single = new Singleton1();  
  4.  
  5.     public static Singleton1 getInstance() {  
  6.         return single;  
  7.     }  
  8. }  



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值