创建型模式一共分为五种:工厂模式,抽象工厂模式,单例模式,建造者模式,还有原型模式
工厂模式和抽象工厂模式一样,都是用于生成对象的工厂,区别是,抽象工厂模式生产的是工厂,由工厂再产生对象,这两种模式的好处是,需要对象的时候,只要在工厂中拿即可,只要知道需求对象的名字,但是,过多的工厂也会造成代码的臃肿,因为要想产生一类对象就需要一个类型的工厂,但需求更多时,工厂的代码也会更繁琐,会增加系统的复杂度(后面会介绍反射模式生成对象)
普通工厂模式代码:(红色部分为反射模式生成对象)
package cn.jxliu.pattern.creational.factory;
public interface Animal {
void eat();
}
package cn.jxliu.pattern.creational.factory;
/**
* 创建工厂用于生成实体类的对象
*
* @author Administrator
* 优点: 1、一个调用者想创建一个对象,只要知道其名称就可以了。
* 2、扩展性高,如果想增加一个产品,只要扩展一个工厂类就可以。
* 3、屏蔽产品的具体实现,调用者只关心产品的接口。
* 缺点:每次增加一个产品时,都需要增加一个具体类和对象实现工厂,使得系统中类的个数成倍增加,在一定程度上增加了系统的复杂度,
* 同时也增加了系统具体类的依赖。
*/
public class AnimalFactory {
/**
* 普通模式
* @param animalType
* @return
*/
public Animal getAnimal(String animalType) {
if (animalType == null) {
return null;
}
if (animalType.equalsIgnoreCase("Cat")) {
return new Cat();
} else if (animalType.equalsIgnoreCase("Dog")) {
return new Dog();
} else if (animalType.equalsIgnoreCase("Tiger")) {
return new Tiger();
}
return null;
}
/**
* 使用反射创建生成对象的工厂的好处,就是当需要生产不同的对象时,不需要再重新创建实体类对象实现接口了
* @param clazz
* @return
*/
public static Object getClass(Class<? extends Animal> clazz){
Object obj = null;
try {
obj = Class.forName(clazz.getName()).newInstance();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return obj;
}
}
package cn.jxliu.pattern.creational.factory;
public class Cat implements Animal {
@Override
public void eat() {
System.out.println("Cat吃的方法!");
}
}
package cn.jxliu.pattern.creational.factory;
public class Dog implements Animal {
@Override
public void eat() {
System.out.println("Dog吃的方法!");
}
}
package cn.jxliu.pattern.creational.factory;
public class Tiger implements Animal {
@Override
public void eat() {
System.out.println("Tiger吃的方法!");
}
}
package cn.jxliu.pattern.creational.factory;
public class FactoryPatternDemo {
public static void main(String[] args) {
AnimalFactory af = new AnimalFactory();
Animal cat = af.getAnimal("Cat");
cat.eat();
Animal dog = af.getAnimal("Dog");
dog.eat();
Animal tiger = af.getAnimal("Tiger");
tiger.eat();
Cat c1 = (Cat)AnimalFactory.getClass(Cat.class);
c1.eat();
}
}
package cn.jxliu.pattern.creational.factory.abs;
/**
* 动物接口
* @author Administrator
*
*/
public interface Animal {
void eat();
}
package cn.jxliu.pattern.creational.factory.abs;
public interface Color {
void fill();
}
package cn.jxliu.pattern.creational.factory.abs;
public class Cat implements Animal {
@Override
public void eat() {
System.out.println("Cat吃的方法!");
}
}
package cn.jxliu.pattern.creational.factory.abs;
/**
* 继承抽象工厂类,重新实现生成对象工厂的方法
* @author Administrator
*
*/
public class AnimalFactory extends AbstractFactory {
@Override
Animal getAnimal(String animalType) {
if(animalType == null){
return null;
}
if(animalType.equalsIgnoreCase("Cat")){
return new Cat();
}else if(animalType.equalsIgnoreCase("Dog")){
return new Dog();
}else if(animalType.equalsIgnoreCase("Tiger")){
return new Tiger();
}
return null;
}
@Override
Color getColor(String colorType) {
return null;
}
/**
* 反射生成动物工厂
* @param clazz
* @return
*/
public static Object getAnimalFactory(Class<? extends Animal> clazz){
Object obj = null;
try {
obj = Class.forName(clazz.getName()).newInstance();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return obj;
}
}
package cn.jxliu.pattern.creational.factory.abs;
public class Black implements Color {
@Override
public void fill() {
System.out.println("Black填充的方法!");
}
}
package cn.jxliu.pattern.creational.factory.abs;
public class Cat implements Animal {
@Override
public void eat() {
System.out.println("Cat吃的方法!");
}
}
package cn.jxliu.pattern.creational.factory.abs;
public interface Color {
void fill();
}
package cn.jxliu.pattern.creational.factory.abs;
/**
* 继承抽象工厂类,重新实现生成对象工厂的方法
* @author Administrator
*
*/
public class ColorFactory extends AbstractFactory {
@Override
Animal getAnimal(String animalType) {
return null;
}
@Override
Color getColor(String colorType) {
if(colorType == null){
return null;
}
if(colorType.equalsIgnoreCase("Green")){
return new Green();
}else if(colorType.equalsIgnoreCase("Red")){
return new Red();
}else if(colorType.equalsIgnoreCase("Black")){
return new Black();
}
return null;
}
/**
* 通过工厂获取对象
* @return
*/
public static Object getColorFactory(Class<? extends Color> clazz){
Object obj = null;
try {
obj = Class.forName(clazz.getName()).newInstance();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return obj;
}
}
package cn.jxliu.pattern.creational.factory.abs;
public class Dog implements Animal {
@Override
public void eat() {
System.out.println("Dog吃的方法!");
}
}
package cn.jxliu.pattern.creational.factory.abs;
public class FactoryProducer{
public static AbstractFactory getFactory(String choice){
if(choice.equalsIgnoreCase("AnimalFactory")){
return new AnimalFactory();
}else if(choice.equalsIgnoreCase("ColorFactory")){
return new ColorFactory();
}
return null;
}
public static Object getAbstractFactory(Class<? extends AbstractFactory> clazz){
Object obj = null;
try {
obj = Class.forName(clazz.getName()).newInstance();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return obj;
}
}
package cn.jxliu.pattern.creational.factory.abs;
public class Green implements Color {
@Override
public void fill() {
System.out.println("Green填充的方法!");
}
}
package cn.jxliu.pattern.creational.factory.abs;
public class Red implements Color {
@Override
public void fill() {
System.out.println("Red填充的方法!");
}
}
package cn.jxliu.pattern.creational.factory.abs;
public class Tiger implements Animal {
@Override
public void eat() {
System.out.println("Tiger吃的方法!");
}
}
单例模式主要分懒汉式和饿汉式两种,单例模式的诞生是用于保证一个类只能有一个对象,具体做法大概为以下三点:一,创建对象的方式私有化;二,构造函数私有化;三,对外类提供一个获取本类对象的方法。
单例模式代码:
package cn.jxliu.pattern.creational.singleton;
/**
* 懒汉式单例模式
* 最大的缺点就是不支持多线程,因为没有加锁synchronized
* @author Administrator
*
*/
public class LazySingleton {
private static LazySingleton single;
private LazySingleton(){}
public static LazySingleton getInstance(){
if(single == null){
single = new LazySingleton();
}
return single;
}
public void eat(){
System.out.println("吃吃次!");
}
}
package cn.jxliu.pattern.creational.singleton;
/**
* 饿汉式单例模式
* 支持多线程,但容易产生垃圾对象
* 优点:没有加锁,执行效率高
* 缺点:类加载时就初始化,浪费内存
* @author Administrator
*
*/
public class HungrySingleton {
private static HungrySingleton singleton = new HungrySingleton();
private HungrySingleton(){}
public static HungrySingleton getInstance(){
return singleton;
}
public void run(){
System.out.println("跑跑跑!");
}
}
package cn.jxliu.pattern.creational.singleton;
/**
* 双检锁/双重校验锁
* 开局初始化,多线程安全,这种采用双锁机制的单例模式,安全,且在多线程下能保持高性能
* @author Administrator
*
*/
public class Singleton {
private volatile static Singleton singleton ;
private Singleton(){}
public static Singleton getInstance(){
if(singleton == null){
synchronized (Singleton.class) {
if(singleton == null){
singleton = new Singleton();
}
}
}
return singleton;
}
}
package cn.jxliu.pattern.creational.singleton;
/**
* 登记式单例类
* 这种方式相对比饿汉式,优点在于只有在显示调用getInstance时,才会初始化singleton,同时支持多线程,实现也比较简单
* @author Administrator
*/
public class RegisterSingleton {
private static class SingletonHolder{
private static final RegisterSingleton INSTANCE = new RegisterSingleton();
}
private RegisterSingleton(){}
/**
* 只有在显示调用RegisterSingleton时,才会初始化实例
* @return
*/
public static final RegisterSingleton getInstance(){
return SingletonHolder.INSTANCE;
}
}
建造者模式主要用于 生成的对象之间具有复杂的内部结构并且对象内部属性本身相互依赖,与工厂模式的区别是:建造者模式更加关注与零件装配的顺序。
建造者模式代码:
package cn.jxliu.pattern.creational.builder;
/**
* 相当于一件商品
* @author Administrator
*
*/
public interface Item {
/**
* 名称的功能
* @return
*/
public String name();
/**
* 价格的功能
* @return
*/
public Float price();
/**
* 打包的功能
* @return
*/
public Packing packing();
}
package cn.jxliu.pattern.creational.builder;
/**
* 用于打包
* @author Administrator
*
*/
public interface Packing {
public String pack();
}
package cn.jxliu.pattern.creational.builder;
public abstract class Burger implements Item {
@Override
public abstract Float price();
/**
* 默认有了打包的功能
*/
@Override
public Packing packing() {
return new PaperPack();
}
}
package cn.jxliu.pattern.creational.builder;
public abstract class Drink implements Item {
@Override
public abstract Float price();
/**
* 默认自带打包功能
*/
@Override
public Packing packing() {
return new BottlePack();
}
}
package cn.jxliu.pattern.creational.builder;
public class HotBurger extends Burger {
@Override
public String name() {
return "一个辣堡!";
}
@Override
public Float price() {
return 3.5f;
}
}
package cn.jxliu.pattern.creational.builder;
public class SweetBurger extends Burger {
@Override
public String name() {
return "一个甜堡!";
}
@Override
public Float price() {
return 5.5f;
}
}
package cn.jxliu.pattern.creational.builder;
public class CokeDrink extends Drink{
@Override
public String name() {
return "一杯咖啡!";
}
@Override
public Float price() {
return 6.8f;
}
}
package cn.jxliu.pattern.creational.builder;
public class TeaDrink extends Drink {
@Override
public String name() {
return "一杯茶!";
}
@Override
public Float price() {
return 10.05f;
}
}
package cn.jxliu.pattern.creational.builder;
/**
* 使用纸杯包装
* @author Administrator
*
*/
public class PaperPack implements Packing{
@Override
public String pack() {
return "使用纸杯包装!";
}
}
package cn.jxliu.pattern.creational.builder;
/**
* 用杯包装
* @author Administrator
*
*/
public class BottlePack implements Packing{
@Override
public String pack() {
return "使用杯包装!";
}
}
package cn.jxliu.pattern.creational.builder;
import java.util.ArrayList;
import java.util.List;
public class Meal {
private List<Item> items = new ArrayList<Item>();
/**
* 添加商品的功能
* @param item
*/
public void addItem(Item item){
items.add(item);
}
/**
* 计算价格
* @return
*/
public Float calculate(){
float f = 0.0f;
for (Item item : items) {
f += item.price();
}
return f;
}
/**
* 展示商品
*/
public void showItems(){
for (Item item : items) {
System.out.print("Item : "+item.name());
System.out.print(", Packing : "+item.packing().pack());
System.out.println(", Price : "+item.price());
}
}
}
package cn.jxliu.pattern.creational.builder;
public class MealFactory {
public static Object getInstance(Class<? extends Meal> clazz){
Object obj = null;
try {
obj = Class.forName(clazz.getName()).newInstance();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return obj;
}
}
package cn.jxliu.pattern.creational.builder;
public class BuilderPatternDemo {
public static void main(String[] args) {
Meal m1 = (Meal)MealFactory.getInstance(Meal.class);
m1.addItem(new HotBurger());
m1.addItem(new CokeDrink());
m1.showItems();
System.out.println("总价为:"+m1.calculate());
Meal m2 = (Meal)MealFactory.getInstance(Meal.class);
m2.addItem(new SweetBurger());
m2.addItem(new TeaDrink());
m2.showItems();
m2.calculate();
System.out.println("总价为:"+m2.calculate());
}
}