设计模式-创建型-静态工厂模式
刚开始接触编程时,总会提到设计模式,在这里将一般定义的设计模式一一进行说明,先从简单的设计模式开始。
创建型-静态工厂模式(并不是Gof得23中设计模式,后来人们扩展的,尽信书不如无书,这也体现了JAVA的魅力)
假设有这样一个工厂,可以生产几种不同类型的笔;我们只向工厂说明一下我们需要的笔型号,工厂就给我们提供相应型号的笔。
假设我们有一个工厂对象(ShapeFactory),可以建几种不同样式的外形(Shape);我们只向工厂对象(ShapeFactory)传我们需要创建的外形(Shape)的参数(如描述参数),对象(ShapeFactory)就给我们创建不同的外形(Shape)。
本文引用W3Cschool中的java教程中设计模式,链接地址https://www.w3cschool.cn/java/java-factory-pattern.html
外形Shape的接口
Shape.java
public interface Shape { void draw(); }
不同类型的外形对象,即Shape接口的实现类
Rectangle.java
public class Rectangle implements Shape { @Override public void draw() { System.out.println("Inside Rectangle::draw() method."); } }
Square.java
public class Square implements Shape { @Override public void draw() { System.out.println("Inside Square::draw() method."); } }
工厂生产的外形(Shape)有了,几种简单的Shape实现类有了(即几种不同的外形),现在就缺少工厂对象(ShapeFactory)了。工厂对象ShapeFactory中我们需要提供一个方法,用来生产几种不同的外形对象。本文方法为getShape(String shapestyle)。
ShapeFactory.java
public class ShapeFactory { public static Shape getShape(String shapestyle) { if(shapestyle==null) { return null; } if("Rectangle".equalsIgnoreCase(shapestyle)) { return new Rectangle(); } if ("Square".equalsIgnoreCase(shapestyle)) { return new Square() ; } return null; } }
好了,到现在为止,我们的工厂已经建好了。怎样用这个工厂呢,现在需要用工厂得到一个Square对象,也比较简单了。在ShapeFactoryTest类中,用ShapeFactory 创建Square对象为例子
ShapeFactoryTest.java
public class ShapeFactoryTest { public static void main(String[] args) { Shape shape = ShapeFactory.getShape("Square"); shape.drow(); } }
程序运行结果
Inside Square::draw() method.
综上,一个静态工厂模式已经完成了。
为什么说ShapeFactoryTest就是静态工厂了呢,这样编程怎么就是静态工厂模式呢?
因为我们自己不单独new Square()和new Rectangle()对象,这个对象由ShapeFactoryTest创建(生产),创建时使用静态方法,所以这种设计的方式被大家叫做静态工厂模式。
为什么要用静态工厂模式呢?在本例子中,不通过Shape shape = shapeFactory.getShape("Square")方式获取Square对象,而是直接用new Square()获取Square对象,不是也行吗?
先回答第二个问题,直接用Shape shape =new Square()的方式获取Shape的实现确实也可行。
再看第一个问题,shapeFactory.getShape("Square")中Square参数是我们直接写的,如果这个参数是外部传递的参数呢?外部传递的参数可能是Square,也可能是Rectangle,这时我们不知道外部传递
什么参数,执行的方法与传参有关,这时候一个静态工厂模式就是需要的了。
对于刚开始接触java的人,这种静态工厂我们有没有接触过呢?
JavaSE是我们学习java是最先接触到的知识了,其实JaveSE中体现了很多种设计模式。在java.nio中,Paths中就包含了两个返回Path对象的静态工厂方法:
Path path1 = Paths.get(URI uri);
Path path2 = Paths.get(String first,String... more);
具体使用也比较简单,大家可以自己写一个简单的Class,在main方法中使用Path path1 = Paths.get(".");导入相应的包之后,查看源代码,看Paths类,相信大家会感觉静态工厂方法其实离我们不远,对
静态工厂方法的体会更加深刻。
例子
public class PathsTest { public static void main(String[] args) { Path path = Paths.get("."); } }
Paths源码
package java.nio.file; import java.nio.file.spi.FileSystemProvider; import java.net.URI; /** * This class consists exclusively of static methods that return a {@link Path} * by converting a path string or {@link URI}. * * @since 1.7 */ public final class Paths { private Paths() { } /** * Converts a path string, or a sequence of strings that when joined form * a path string, to a {@code Path}. If {@code more} does not specify any * elements then the value of the {@code first} parameter is the path string * to convert. If {@code more} specifies one or more elements then each * non-empty string, including {@code first}, is considered to be a sequence * of name elements (see {@link Path}) and is joined to form a path string. * The details as to how the Strings are joined is provider specific but * typically they will be joined using the {@link FileSystem#getSeparator * name-separator} as the separator. For example, if the name separator is * "{@code /}" and {@code getPath("/foo","bar","gus")} is invoked, then the * path string {@code "/foo/bar/gus"} is converted to a {@code Path}. * A {@code Path} representing an empty path is returned if {@code first} * is the empty string and {@code more} does not contain any non-empty * strings. * * <p> The {@code Path} is obtained by invoking the {@link FileSystem#getPath * getPath} method of the {@link FileSystems#getDefault default} {@link * FileSystem}. * * <p> Note that while this method is very convenient, using it will imply * an assumed reference to the default {@code FileSystem} and limit the * utility of the calling code. Hence it should not be used in library code * intended for flexible reuse. A more flexible alternative is to use an * existing {@code Path} instance as an anchor, such as: * <pre> * Path dir = ... * Path path = dir.resolve("file"); * </pre> * * @param first * the path string or initial part of the path string * @param more * additional strings to be joined to form the path string * * @return the resulting {@code Path} * * @throws InvalidPathException * if the path string cannot be converted to a {@code Path} * * @see FileSystem#getPath */ public static Path get(String first, String... more) { return FileSystems.getDefault().getPath(first, more); } /** * Converts the given URI to a {@link Path} object. * * <p> This method iterates over the {@link FileSystemProvider#installedProviders() * installed} providers to locate the provider that is identified by the * URI {@link URI#getScheme scheme} of the given URI. URI schemes are * compared without regard to case. If the provider is found then its {@link * FileSystemProvider#getPath getPath} method is invoked to convert the * URI. * * <p> In the case of the default provider, identified by the URI scheme * "file", the given URI has a non-empty path component, and undefined query * and fragment components. Whether the authority component may be present * is platform specific. The returned {@code Path} is associated with the * {@link FileSystems#getDefault default} file system. * * <p> The default provider provides a similar <em>round-trip</em> guarantee * to the {@link java.io.File} class. For a given {@code Path} <i>p</i> it * is guaranteed that * <blockquote><tt> * Paths.get(</tt><i>p</i><tt>.{@link Path#toUri() toUri}()).equals(</tt> * <i>p</i><tt>.{@link Path#toAbsolutePath() toAbsolutePath}())</tt> * </blockquote> * so long as the original {@code Path}, the {@code URI}, and the new {@code * Path} are all created in (possibly different invocations of) the same * Java virtual machine. Whether other providers make any guarantees is * provider specific and therefore unspecified. * * @param uri * the URI to convert * * @return the resulting {@code Path} * * @throws IllegalArgumentException * if preconditions on the {@code uri} parameter do not hold. The * format of the URI is provider specific. * @throws FileSystemNotFoundException * The file system, identified by the URI, does not exist and * cannot be created automatically, or the provider identified by * the URI's scheme component is not installed * @throws SecurityException * if a security manager is installed and it denies an unspecified * permission to access the file system */ public static Path get(URI uri) { String scheme = uri.getScheme(); if (scheme == null) throw new IllegalArgumentException("Missing scheme"); // check for default provider to avoid loading of installed providers if (scheme.equalsIgnoreCase("file")) return FileSystems.getDefault().provider().getPath(uri); // try to find provider for (FileSystemProvider provider: FileSystemProvider.installedProviders()) { if (provider.getScheme().equalsIgnoreCase(scheme)) { return provider.getPath(uri); } } throw new FileSystemNotFoundException("Provider \"" + scheme + "\" not installed"); } }
posted on 2019-05-14 16:32 xingshouzhan 阅读(183) 评论(0) 编辑 收藏 举报