设计模式探索——工厂模式

来源:互联网 发布:淘宝莆田鞋 编辑:程序博客网 时间:2024/06/14 16:41

一、工厂方法模式

关于UML图
这里写图片描述
典型应用:

class Engine{    public void getStyle(){        System.out.println("这是汽车的发动机");    }}class Underpan{    public void getStyle(){        System.out.println("这是汽车的底盘");    }}class Wheel{    public void getStyle(){        System.out.println("这是汽车的轮胎");    }}public class Client{    public static void main(String[] args){        Engine engine = new Engine();        Underpan underpan = new Underpan();        Wheel wheel = new Wheel();        ICar car = new Car(engine,underpan,wheel);        car.show();    }}

这些产品的话可以继承来自同一个的接口,这里可以看出来的就是,客户和产品之间的耦合度是很高的,所以我们需要怎么做呢;

interface IFactory{    public ICar createCar();}calss Factory implements IFactory{    public ICar createCar(){        Engine engine = new Engine();        Underpan underpan = new Underpan();        Wheel wheel = new Wheel();        ICar car = new Car(engine,underpan,wheel);        return car;    }}public class Client{    public static void main(String[] args){        IFactory factory = new Factory();        ICar car = factory.createCar();        car.show();    }}

使用工厂方法之后,客户端和产品之间的耦合度大大降低了的。

工厂方法模式就是:就是很多的产品继承自同一个接口规范,通过工厂来可以创建不同的产品(这些产品是属于同一的类型的);

二、抽象工厂模式

首先看UML图
这里写图片描述

interface IProduct1{    public void show();}interface IProduct2{    public void show();}class Product1 implements IProduct1{    public void show(){        System.out.println("这是1型产品");    }}class Product2 implements IProduct2{    public void show(){        System.out.println("这是2型产品");    }}interface IFactory{    public IProduct1 createProduct1();    public IProduct2 createProduct2();}clacc Factory implements IFactory{    public IProduct1 createProduct1(){        return new Product1();    }    public IProduct2 createProduct2(){        return new Product2();    }}public class Client{    public static void main(String[] args){        IFactory factory = new Factory();        factory.createProduct1().show();        factory.createProduct2().show();    }}

抽象工厂模式的话就是不同的产品类型关联在不同的工厂中,这些工厂继承自一个抽象的工厂,这样子就严格的区分开来不同的产品类型了,同样如果要添加新的产品的话同样需要修改抽象工厂类

0 0
原创粉丝点击