1. Design mode----------> Factory mode:
Sender.java
Package Me.ele.mytest;public interface sender{public void Send ();}
2.MailSend
Package Me.ele.mytest;public class MailSend implements sender{@Override public void Send () {System.out. println ("This is mail Send"); }}
3.SmsSend
Package Me.ele.mytest;public class Smssend implements sender{@Override public void Send () {SYSTEM.OUT.P Rintln ("This is Sms Send"); }}
4.TestFactory
Package Me.ele.mytest;public class Testfactory {public Sender produce (String type) {if (Type.equals ("Mail")) { return new MailSend (); } else if (Type.equals ("Sms")) {return new smssend (); } else {System.out.println ("Please enter the correct type"); return null; } }}
5.main.java
Package Me.ele.mytest;public class Main {public static void main (string[] args) {System.out.println ("Start Test factory design mode "); System.out.println ("===================="); Testfactory t = new testfactory (); Sender S1 = t.produce ("Mail"); Sender s2 = t.produce ("Sms"); S1.send (); S2.send (); System.out.println ("===================="); }}
6. Result
Start test Factory design mode ====================this is Mail sendthis is Sms send====================
7. The above patterns need to match the characters, it is more inconvenient. You can use the abstract Factory mode to
New Provider Interface
Package Me.ele.mytest;public interface Provider {public Sender produce ();}
Added sendmailfactory and sendsmsfactory classes to implement the provider interface
Package Me.ele.mytest;public class Sendmailfactory implements Provider {@Override public Sender produce () { return new MailSend (); }}
Package Me.ele.mytest;public class Sendsmsfactory implements provider{@Override public Sender Produce () {RET Urn new Smssend (); }}
Modify the Main method:
Package Me.ele.mytest;public class Main {public static void main (string[] args) {System.out.println ("Start Test factory design mode "); System.out.println ("===================="); Provider S1 = new Sendmailfactory (); Provider s2 = new Sendsmsfactory (); S1.produce (). Send (); S2.produce (). Send (); System.out.println ("===================="); }}
return results
Start test Factory design mode ====================this is Mail sendthis is Sms send====================
The above in the implementation of the factory model, only need to add the interface can be without changing the source code, the easy expansion of the new interface
Factory mode is used when a large number of products need to be created, but there is a common interface
Java Learning Notes-----The factory pattern of design patterns