工厂模式
来源:互联网 发布:生活中的人工智能产品 编辑:程序博客网 时间:2024/05/16 02:07
1.普通工厂模式:对实现了同一接口不同类实现实例的创建
首先,创建接口
public interface Sender { public void send();}
其次,创建实现类
public class InfoSender implements Sender { public void send() { System.out.println("this is the InfoSender"); }}
public class MailSender implements Sender { public void send() { System.out.println("this is the MailSender"); }}
最后,创建工厂类
public class SendFactory { public Sender produce(String type) { if ("mail".equals(type)) { return new MailSender(); } else if ("info".equals(type)) { return new InfoSender(); } return null; }}
public class TestSendFactory { public static void main(String[] args) { SendFactory sendFactory = new SendFactory();<span style="white-space: pre;"></span>Sender sender=sendFactory.produce("mail"); sender.send(); }}
缺点:如果传递的字符串type出错,则不能创建正确的对象
2.多个工厂模式:对实现了同一接口不同类实现实例的创建,解决了普通工程模式字符串输入错误导致的问题
工厂类
public class SendFactory { public Sender produceMailSend() { return new MailSender(); } public Sender produceInfoSend() { return new InfoSender(); }}
测试类如下
public class TestSendFactory { public static void main(String[] args) { SendFactory sendFactory = new SendFactory(); Sender sender=sendFactory.produceInfoSend(); sender.send(); }}
3.静态工厂方法模式:将工厂类中方法置为static的
工厂类
public class SendFactory { public static Sender produceMailSend() { return new MailSender(); } public static Sender produceInfoSend() { return new InfoSender(); }}
测试类
<span style="color:#333333;">public class TestSendFactory { public static void main(String[] args) { Sender sender=SendFactory.produceInfoSend(); sender.send(); }}</span>
总之:工厂方法模式适合于实现同一接口多个类实例需要创建时使用,普通工厂方法传入字符串容易出错,多方法工厂要创建多个实例,静态工厂方法最好,但是工厂模式有个弊端,如果要扩展程序,就要修改工厂类,
2.抽象工厂模式:有多个工厂,修复了工厂模式程序不易于扩展缺点
增肌一个接口
<span style="color:#333333;">public interface FactoryProvider { public Sender produceFactory();}</span>
工厂类
<span style="color:#333333;">public class SendInfoFactory implements FactoryProvider { public Sender produceFactory() { return new InfoSender(); }}</span>
<span style="color:#333333;">public class SendMailFactory implements FactoryProvider { public Sender produceFactory() { return new MailSender(); }}</span>
测试类
<span style="color:#333333;">public class TestSendFactory { public static void main(String[] args) { FactoryProvider factoryProvider = new SendMailFactory(); Sender sender = factoryProvider.produceFactory(); sender.send(); }}</span>
优点:如果要增加发送图片功能,只需要增加一个实现类实现Sender接口,增加一个工厂类实现FactoryProvider()接口,这样程序扩展性好
具有不同属性的Builder类
public class Builder { private List<Sender> list = new LinkedList<Sender>(); public void produceMailSender(int num) { for (int i = 0; i < num; ++i) { MailSender mailSender = new MailSender(); mailSender.send(); list.add(mailSender); } } public void produceInfoSender(int num) { for (int i = 0; i < num; ++i) { InfoSender infoSender = new InfoSender(); infoSender.send(); list.add(infoSender); } }}
测试类
public class TestSendFactory { public static void main(String[] args) { Builder builder = new Builder(); builder.produceInfoSender(10); }}
6.原型模式:将源对象复制为相似的对象
浅复制:基本数据类型复制,引用类型还是指向原来的对象
深复制:基本数据类型,引用类型都复制,不再指向源对象
public class Prototype implements Cloneable, Serializable { private String name; private SerializableObject object; public Prototype(){ object =new SerializableObject(); } //浅复制 public Object clone() { Prototype prototype = null; try { prototype = (Prototype) super.clone(); } catch (CloneNotSupportedException e) { e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } return prototype; } //深复制 public Object deepClone() { try { ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream); objectOutputStream.writeObject(this); ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray()); ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream); return objectInputStream.readObject(); } catch (Exception e) { e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } return null; } private class SerializableObject implements Serializable { } public static void main(String[] args) { Prototype prototype = new Prototype(); Prototype prototype1= (Prototype)prototype.clone(); System.out.println(prototype1.object); prototype1 = (Prototype)prototype.deepClone(); System.out.println(prototype1.object); } public String getName() { return name; } public void setName(String name) { this.name = name; } public SerializableObject getObject() { return object; } public void setObject(SerializableObject object) { this.object = object; }}
6.适配器模式:将某个类A的方法以接口的方法表示,类A没有实现该接口,分为类的适配器模式、对象适配器模式、接口适配器模式
类的适配器模式如下:
某个类A方法
public class Source { public void method1(){ System.out.println("method1()"); }}
某个接口方法
public interface Target { public void method1(); public void method2();}
继承类A,实现Target接口类
public class Adapter extends Source implements Target { public void method2() { //To change body of implemented methods use File | Settings | File Templates. }}
测试类
public class TestAdapter { public static void main(String[] args) { Target target = new Adapter(); target.method1(); target.method2(); }}
这样Target接口的实现类Adapter,就有了Source类方法method1()的功能
对象适配器模式如下:持有Source类的实例
public class Adapter implements Target { private Source source; public Adapter(Source source) { this.source = source; } public void method1() { this.source.method1(); } public void method2() { //To change body of implemented methods use File | Settings | File Templates. }}
测试类
public class TestAdapter { public static void main(String[] args) { Source source = new Source(); Target target = new Adapter(source); target.method1(); target.method2(); }}
接口适配器模式:有时类实现一个接口,但是并不需要接口中的所有方法,但是接口中的所有方法都必须实现,此时可以定义一个抽象类,实现接口,其他类继承抽象类,实现自己需要方法即可
抽象类如下:
public abstract class AbstactClass implements Target{ public void method1() { } public void method2() { }}
实现类如下:
public class Adapter1 extends AbstactClass { public void method2() { System.out.println("method2"); }}
public class Adapter extends AbstactClass { public void method1() { System.out.println("method1"); }}
测试类如下:
public class TestAdapter { public static void main(String[] args) { Target target = new Adapter(); target.method1(); target.method2(); Target target1 = new Adapter1(); target1.method1(); target1.method2(); }}
8.装饰模式:给被装饰对象动态增加一些新的功能,装饰对象持有被装饰对象的实例,被装饰类以及装饰类都实现相同接口,缺点是产生过多相似的装饰对象(给被装饰对象增加不同功能),
被装饰类:
public class BeDecorator implements Target { public void method1() { System.out.println("method1"); }}
装饰类:
public class Decorator implements Target { public BeDecorator beDecorator; public Decorator(BeDecorator beDecorator) { this.beDecorator = beDecorator; } public void method1() { System.out.println("装饰前"); beDecorator.method1(); System.out.println("装饰后"); }}
测试类
public class TestAdapter { public static void main(String[] args) { BeDecorator beDecorator = new BeDecorator(); Target target = new Decorator(beDecorator); target.method1(); }}
10.代理模式:创建一个代理类,替源对象进行一些新增功能操作,例如中介替我们去找房子
被代理类:
public class Source implements Target{ public void method1(){ System.out.println("method1()"); }}
代理类
public class Proxy implements Target { public Source source; public Proxy() { this.source = new Source(); } public void method1() { beforeProxy(); this.source.method1(); afterProxy(); } private void afterProxy() { System.out.println("afterProxy"); } private void beforeProxy() { System.out.println("beforeProxy"); }}
测试类
public class TestAdapter { public static void main(String[] args) { Target target = new Proxy(); target.method1(); }}
11.外观模式:解决类与类之间依赖关系,降低耦合度,例如通过spring配置文件,降低类之间耦合度,外观模式不涉及接口
public class Cpu { public void start(){ System.out.println("cpu start"); }}
public class Memory { public void start(){ System.out.println("Memory start"); }}
public class ComPuter { public Cpu cpu; public Memory memory; public ComPuter() { this.cpu = new Cpu(); this.memory = new Memory(); } public void start() { cpu.start(); memory.start(); }}
测试类
public class TestAdapter { public static void main(String[] args) { ComPuter comPuter = new ComPuter(); comPuter.start(); }}
如果没有ComPuter类,那么Cpu类start时,需要Memory先调用start()方法,这样Cpu与Memory之间耦合度增加
12.策略模式:定义一系列算法,给用户使用,算法已经封装好了,定义一个抽象类(辅助类),实现类extend抽象类,实现接口,适用于算法决策系统中
public interface Target { public int calculate(String exp);}
public class Plus extends AbStractStrategy implements Target { public int calculate(String exp) { int[] ints = spilt(exp, "\\+"); return ints[0] + ints[1]; //To change body of implemented methods use File | Settings | File Templates. }}
public class Minus extends AbStractStrategy implements Target { public int calculate(String exp) { int[] ints = spilt(exp, "\\-"); return ints[0] - ints[1]; //To change body of implemented methods use File | Settings | File Templates. }}
测试类:
public class TestStrategy { public static void main(String[] args) { Target target = new Minus(); System.out.println(target.calculate("2-8")); }}
13.责任链模式:一个事件处理流,一个对象链接环,事情处理在对象中传递,知道某个对象处理完逻辑,返回,每个对象都有下个对象的引用,形成一个链路,客户端请求的请求不知道被哪个对象处理,适用于动态调整系统场景(对用户来说是透明的)
public abstract class AbStractStrategy { private Target target; public Target getTarget() { return target; } public void setTarget(Target target) { this.target = target; }}
public class Minus extends AbStractStrategy implements Target { private String name; public Minus(String name){ this.name = name; } public int calculate(String exp) { System.out.println(name+"deal"); if(getTarget()!=null){ getTarget().calculate("//+"); } return 0; //To change body of implemented methods use File | Settings | File Templates. }}
测试类:
public class TestStrategy { public static void main(String[] args) { Minus minus1 = new Minus("minus1"); Minus minus2 = new Minus("minus2"); Minus minus3 = new Minus("minus3"); minus1.setTarget(minus2); minus2.setTarget(minus3); minus2.calculate("2+8"); }}
14.模板模式:创建一个抽象类,定义一个主方法,以及一个抽象方法,当抽象类调用主方法时,实现对抽象类子类方法的调用
public abstract class AbStractStrategy { //主方法 public int process(int num1, int num2) { return calculate(num1, num2); } protected abstract int calculate(int num1, int num2);}
public class Minus extends AbStractStrategy { @Override protected int calculate(int num1, int num2) { return num1+num2; }}
测试类:
public class TestStrategy { public static void main(String[] args) { AbStractStrategy abStractStrategy = new Minus(); System.out.print(abStractStrategy.process(1,2)); }}
15.观察者模式:购物网站上用户添加到货通知后,商品有货后,就会主动通知订阅到货通知的用户
public interface Observer { public void update();}
public class Observer1 implements Observer { public void update() { System.out.println("Observer1 has received notify"); }}
public class Observer2 implements Observer { public void update() { System.out.println("Observer2 has received notify"); }}
对用户操作接口:
public interface Subject { public void add(Observer observer); public void del(Observer observer); public void notifyAllObservers(); public void operation();}
public class AbstractObserver implements Subject { private Vector<Observer> vector = new Vector<Observer>(); public void add(Observer observer) { vector.add(observer); } public void del(Observer observer) { vector.remove(observer); } public void notifyAllObservers() { Iterator<Observer> iterator = (Iterator<Observer>) vector.iterator(); while (iterator.hasNext()) { Observer observer = iterator.next(); observer.update(); } } public void operation() { //To change body of implemented methods use File | Settings | File Templates. }}
public class MySubject extends AbstractObserver { public void operation(){ notifyAllObservers(); }}
public class Test { public static void main(String[] args) { Subject subject = new MySubject(); subject.add(new Observer1()); Observer2 observer2=new Observer2(); subject.add(observer2); subject.operation(); System.out.println("============="); subject.del(observer2); subject.operation(); }}
如果要增加其他通知类型,可以在Observer接口新增方法,例如消息推送,
16.迭代器模式:先顺序访问对象,再对对象中元素遍历访问,例如Iterator ite=Collection.iterator ite.hasNext();
public interface Iterator { public Object previous(); public Object next(); public boolean hasNext(); public Object first();}
public interface Collection { public Iterator iterator(); public Object get(int i); public int size();}
Collection中可以获取Iterator
public class MyCollection implements Collection { String[] strings = {"a","b","c"}; public Iterator iterator() { return new MyIterator(this); //To change body of implemented methods use File | Settings | File Templates. } public Object get(int i) { return strings[i]; //To change body of implemented methods use File | Settings | File Templates. } public int size() { return strings.length; //To change body of implemented methods use File | Settings | File Templates. }}
public class MyIterator implements Iterator { private int pos = -1; private Collection collection; public MyIterator(Collection collection) { this.collection = collection; } public Object previous() { if (pos > 0) { pos--; } return collection.get(pos); //To change body of implemented methods use File | Settings | File Templates. } public Object next() { if (pos < collection.size() - 1) { pos++; } return collection.get(pos); //To change body of implemented methods use File | Settings | File Templates. } public boolean hasNext() { if (pos < collection.size() - 1) { return true; } return false; } public Object first() { if (collection.size() > 0) { return collection.get(0); } return null; }}
测试类:
public class Test { public static void main(String[] args) { Collection collection = new MyCollection(); Iterator iterator = collection.iterator(); while (iterator.hasNext()) { System.out.println(iterator.next()); } }}
22
- 工厂模式 -- 工厂方法
- 工厂模式 -- 抽象工厂
- 工厂模式-简单工厂
- 工厂模式-工厂方法
- 工厂模式:静态工厂
- 工厂模式-简单工厂
- 工厂模式-抽象工厂
- 工厂模式-工厂方法
- 工厂 > 工厂方法模式
- 工厂模式-静态工厂
- 工厂模式-抽象工厂
- 工厂模式
- 工厂模式
- 工厂模式
- 工厂模式
- 工厂模式
- 工厂模式
- 工厂模式
- 剑指offer:单链表的基本操作
- Drupal7做一个双语站
- js 技术自学
- vss(2005)使用详解
- fopen\fread\fwrite\fscanf\fprintf\fseek\feof\rewind\fgets\fputc等系列函数使用总结
- 工厂模式
- 单词分割
- 一个合格的程序员应该读过哪些书
- 好开心哦
- POJ 2612 Mine Sweeper 模拟
- Xcode 快捷键
- Android TextView中文字通过SpannableString来设置超链接、颜色、字体等属性
- 白话机器学习算法(十七)熵,条件熵
- HDU 1879 继续畅通工程.