创建型模式
Factory--工厂模式
简单工厂模式
创建工厂对象,然后通过条件获取相应的对象,这种方式健壮性差,如果输入的条件字符串不符合要求则不能获取到相应的对象。
interface Pet {
public void eat();
}
class Dog implements Pet {
@Override
public void eat() {
System.out.print("Dog is eat");
}
}
class Cat implements Pet {
@Override
public void eat() {
System.out.print("Cat is eat");
}
}
class PetFactory {
public Pet getPet(String name) {
if(name.equals("Dog")) {
return new Dog();
}else if (name.equals("Cat")) {
return new Cat();
}else {
// 条件都不符合,创建默认对象
return new Dog();
}
}
}
public class FactoryModel {
public static void main(String[] args) {
PetFactory petFactory = new PetFactory();
Pet dog = petFactory.getPet("Dog");
dog.eat();
}
}
对普通工厂方法模式的改进,在普通工厂方法模式中,如果传递的字符串出错,则不能正确创建对象,提供多个工厂方法,分别创建对象。
interface Pet {
public void eat();
}
class Dog implements Pet {
@Override
public void eat() {
System.out.print("Dog is eat");
}
}
class Cat implements Pet {
@Override
public void eat() {
System.out.print("Cat is eat");
}
}
class PetFactory {
public Pet getDog() {
return new Dog();
}
public Pet getCat() {
return new Cat();
}
}
public class FactoryModel {
public static void main(String[] args) {
PetFactory petFactory = new PetFactory();
Pet dog = petFactory.getDog();
dog.eat();
}
}
多个工厂方法模式
有时需要新增一个或多个种类,例如新加一个Bird动物,可实现动物接口,以及实现工厂类,这样就不需要去修改其他的接口了。
interface Pet {
public void eat();
}
class Dog implements Pet {
@Override
public void eat() {
System.out.print("Dog is eat");
}
}
class Cat implements Pet {
@Override
public void eat() {
System.out.print("Cat is eat");
}
}
interface Factory {
public Pet produce();
}
class DogFactory implements Factory {
@Override
public Pet produce() {
return new Dog();
}
}
class CatFactory implements Factory {
@Override
public Pet produce() {
return new Cat();
}
}
public class AbstractFactoryModel {
public static void main(String[] args) {
Factory factory = new DogFactory();
Pet dog = factory.produce();
dog.eat();
}
}
AbstractFactory--抽象工厂模式
抽象工厂模式中弥补了工厂模式的不足(一个工厂只能生产一种产品)。工厂模式中一个工厂只能生产一种产品,而抽象工厂可以生产多个。
package AbstractFactoryModel;
interface Pet {
public void eat();
}
interface Dog extends Pet {
}
interface Cat extends Pet{
}
class ChinaDog implements Dog {
@Override
public void eat() {
System.out.println("China dog is eat...");
}
}
class ForeignDog implements Cat {
@Override
public void eat() {
System.out.println("Foreign dog is eat...");
}
}
class ChinaCat implements Cat {
@Override
public void eat() {
System.out.println("China cat is eat...");
}
}
class ForeignCat implements Cat {
@Override
public void eat() {
System.out.println("Foreign cat is eat...");
}
}
interface PetFactory {
public Pet produceDog();
public Pet produceCat();
}
class ChinaFactory implements PetFactory {
@Override
public Pet produceDog() {
return new ChinaDog();
}
@Override
public Pet produceCat() {
return new ChinaCat();
}
}
class ForeignFactory implements PetFactory {
@Override
public Pet produceDog() {
return new ForeignDog();
}
@Override
public Pet produceCat() {
return new ForeignCat();
}
}
public class AbstractFactoryModel {
public static void main(String[] args) {
PetFactory chinaFactory = new ChinaFactory();
Pet dog = chinaFactory.produceDog();
dog.eat();
}
}
Singleton--单例模式
单例对象能保证在一个JVM中,该对象只有一个实例存在。
饿汉模式
直接创建该对象,不是懒加载。
class SingletonModel {
private static SingletonModel singleton = new SingletonModel();
private SingletonModel() {
}
public static SingletonModel getInstance() {
return singleton;
}
}
public class HungarySingletonModel {
public static void main(String[] args) {
SingletonModel instance = SingletonModel.getInstance();
}
}
懒汉模式
只有需要用到该对象才创建。使用双重检查锁机制。在还没有该对象的时候,第一次判断为空,此时可能会有多个线程进入到这,也就是说多个线程都判断为空成立,此时某个线程获得锁资源,待该线程释放锁,会有下一个线程获得锁资源,如果不再次判断是否为空,则之后的线程会再次创建对象,此时第一个获得锁资源的线程已经创建了对象,则再次判断可以避免再次创建对象。
class SingletonModel {
private static SingletonModel singleton = null;
private SingletonModel() {
}
public static SingletonModel getInstance() {
if (singleton == null) {
synchronized (singleton) {
if (singleton == null) {
singleton = new SingletonModel();
}
}
}
return singleton;
}
}
public class LazySingletonModel {
public static void main(String[] args) {
SingletonModel instance = SingletonModel.getInstance();
}
}
Builder--建造者模式
将一个复杂对象的构建与它的属性分离,使得同样的构建过程可以创建不同的属性。
目的是将构建复杂对象的过程和它的属性解耦。
类比房子,房子是个对象,而屋顶和地基都是房子的属性,而建造屋顶和地基都有单独的方法实现。
工厂模式关注的是创建单个产品,而建造者模式则关注创建复杂的对象,包含多个部分。
class House {
private String roof;
private String foundation;
public String getRoof() {
return roof;
}
public void setRoof(String roof) {
this.roof = roof;
}
public String getFoundation() {
return foundation;
}
public void setFoundation(String foundation) {
this.foundation = foundation;
}
}
interface Builder {
void buildRoof();
void buildFoundation();
House createHouse();
}
class HouseBuilder implements Builder {
private House house;
public HouseBuilder(House house) {
this.house = house;
}
@Override
public void buildRoof() {
this.house.setRoof("roof");
}
@Override
public void buildFoundation() {
this.house.setFoundation("foundation");
}
@Override
public House createHouse() {
return this.house;
}
}
class Director {
private Builder builder;
public Director(Builder builder) {
this.builder = builder;
}
public House construct() {
builder.buildRoof();
builder.buildFoundation();
return builder.createHouse();
}
}
public class BuilderModel {
public static void main(String[] args) {
House house = new House();
Builder builder = new HouseBuilder(house);
Director director = new Director(builder);
house = director.construct();
System.out.println(house);
}
}
Prototype--原型模式
定义:用原型实例通过拷贝创建新的对象。Prototype模式允许一个对象再创建另外一个可定制的对象,根部无需知道任何创建的细节,工作原理:通过将一个原型对象传给创建方法,从而通过对原型对象的拷贝来创建新的对象。
浅复制
class Pet implements Cloneable{
private String name;
private int age;
public Pet(String name, int age) {
this.name = name;
this.age = age;
}
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
public class PrototypeModel {
public static void main(String[] args) {
Pet pet = new Pet("Tom", 1);
System.out.println("Pet'address is " + pet.toString());
try {
Pet clone_pet = (Pet) pet.clone();
System.out.println("Clone pet'address is " + clone_pet.toString());
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
}
}
深复制
package PrototypeModel;
import java.io.*;
class Dog implements Serializable{
private String name;
private int age;
public Dog(String name, int age) {
this.name = name;
this.age = age;
}
public void introduce() {
System.out.println(this.name + "'age is " + this.age);
}
public Dog clone() {
try {
// 创建一个字节数组输出流用来保存序列化后对象的字节
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
// 创建一个对象输出流
ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
// 将对象写出到之前创建的字节输出流中
objectOutputStream.writeObject(this);
// 将字节数组输出流转化为字节数组
byte[] bytes = byteArrayOutputStream.toByteArray();
// 创建一个字节输入流,将上面的对象字节写入到流中
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes);
// 创建一个对象输入流,将字节输入流包装
ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream);
// 从流中将对象写出来,强转为该对象类型
Dog dog = (Dog) objectInputStream.readObject();
return dog;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
public class DeepPrototypeModel {
public static void main(String[] args) {
Dog dog = new Dog("Tom", 2);
dog.introduce();
System.out.println(dog.toString());
Dog cloneDog = dog.clone();
cloneDog.introduce();
System.out.println(cloneDog.toString());
}
}
结构型模式
Adapter--适配器模式
类适配器
通过继承来实现适配器功能
interface Usb {
void isUsb();
}
interface Ps2 {
void isPs2();
}
class Usber implements Usb {
@Override
public void isUsb() {
System.out.println("Usb接口");
}
}
class Adapter extends Usber implements Ps2 {
@Override
public void isPs2() {
System.out.println("Ps2接口");
}
}
public class ClassAdapter {
public static void main(String[] args) {
Adapter p = new Adapter();
p.isPs2();
p.isUsb();
}
}
对象适配器
通过对象实例来实现适配器功能
interface Usb {
void isUsb();
}
interface Ps2 {
void isPs2();
}
class Usber implements Usb {
@Override
public void isUsb() {
System.out.println("Usb接口");
}
}
class Adapter implements Ps2 {
private Usber usb;
public Adapter(Usber usb) {
this.usb = usb;
}
@Override
public void isPs2() {
System.out.println("Ps2接口");
}
public void isUsb() {
this.usb.isUsb();
}
}
public class ObjectAdapter {
public static void main(String[] args) {
Adapter adapter = new Adapter(new Usber());
adapter.isPs2();
adapter.isUsb();
}
}
接口适配器
如果需要定义一个类,且只需要接口中部分方法,可以使用抽象类去实现接口,然后使用该类去继承抽象类,就可以去重写部分方法了。
interface People {
void eat();
void run();
}
abstract class Adapter implements People {
@Override
public void eat() {
}
@Override
public void run() {
}
}
class Baby extends Adapter {
@Override
public void eat() {
System.out.println("I can eat!");
}
}
class InterfaceAdapterModel {
public static void main(String[] args) {
Baby baby = new Baby();
baby.eat();
}
}
Bridge--桥接模式
桥接模式就是把事物和其具体实现分开,使他们可以各自独立的变化。像常用的JDBC桥DriverManager一样,JDBC进行连接数据库的时候,在各个数据库之间进行切换。
interface JDBC {
void connect();
}
class mysql implements JDBC {
@Override
public void connect() {
System.out.println("connect mysql...");
}
}
class oracle implements JDBC {
@Override
public void connect() {
System.out.println("connect oracle...");
}
}
abstract class Bridge {
private JDBC jdbc;
public void connect() {
jdbc.connect();
}
public JDBC getJdbc() {
return jdbc;
}
public void setJdbc(JDBC jdbc) {
this.jdbc = jdbc;
}
}
class MyBridge extends Bridge {
@Override
public void connect() {
super.connect();
}
}
public class BridgeModel {
public static void main(String[] args) {
Bridge bridge = new MyBridge();
JDBC jdbc = new mysql();
bridge.setJdbc(jdbc);
bridge.connect();
JDBC oracle = new oracle();
bridge.setJdbc(oracle);
bridge.connect();
}
}
Composite--组合模式
将对象以树形组织起来,以达成“部分-整体”的层次结构,使得客户端对单个对象 和组合对象的使用具有一致性。