工厂方法模式将工厂也进行抽象化,产品类的实例化又对应的子工厂实例化。
例子如下:
代码实现如下:
1.定义Log接口
1 2 3 4 5 6 7 8
| package com.notejava.factory.simple;
public interface Log { void write(); }
|
2.定义FileLog类
1 2 3 4 5 6 7 8 9 10
| package com.notejava.factory.simple;
public class FileLog implements Log { public void write() { System.out.println("write to file"); } }
|
3.定义DatabaseLog类
1 2 3 4 5 6 7 8 9 10
| package com.notejava.factory.simple;
public class DatabaseLog implements Log { public void write() { System.out.println("write to database"); } }
|
4.定义LogFactory类
1 2 3 4 5 6 7 8
| package com.notejava.factory.method;
public interface LogFactory { Log createLog(); }
|
5.定义FileLogFactory类
1 2 3 4 5 6 7 8 9 10
| package com.notejava.factory.method;
public class FileLogFactory implements LogFactory { public Log createLog() { return new FileLog(); } }
|
6.定义DatabaseLogFactory类
1 2 3 4 5 6 7 8 9 10
| package com.notejava.factory.method;
public class DatabaseLogFactory implements LogFactory { public Log createLog() { return new DatabaseLog(); } }
|
7.定义Demo类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| package com.notejava.factory.method;
public class Demo { public static void main(String\[\] args) { FileLogFactory fileLogFactory = new FileLogFactory(); Log fileLog = fileLogFactory.createLog(); fileLog.write();
DatabaseLogFactory databaseLogFactory = new DatabaseLogFactory(); Log databaseLog = databaseLogFactory.createLog(); databaseLog.write(); } }
|