- // 简单工厂
- class SimpleFactory {
- public static Product createProduct(String type) {
- if ("A".equals(type)) {
- return new ProductA();
- } else if ("B".equals(type)) {
- return new ProductB();
- } else {
- return null;
- }
- }
- }
- // 工厂方法
- abstract class ProductFactory {
-
- /**
- * 创建产品
- *
- * @return
- */
- abstract Product createProduct();
-
- public Product getObject() {
- Product product = createProduct();
- return product;
- }
- }
-
- class NonCreateProductA extends ProductFactory {
-
- @Override
- Product createProduct() {
- return new ProductA();
- }
- }
-
- class NonCreateProductB extends ProductFactory {
-
- @Override
- Product createProduct() {
- return new ProductB();
- }
- }
- // 实例代码
- interface Product {
- String getName();
- }
-
- class ProductA implements Product {
-
- @Override
- public String getName() {
- return "Name's product A";
- }
- }
-
- class ProductB implements Product {
-
- @Override
- public String getName() {
- return "Name's product B";
- }
- }
测试代码
- public class FactoryMethodTest {
- public static void main(String[] args) {
- // 简单工厂测试代码
- Product simpleA = SimpleFactory.createProduct("A");
- System.out.println(simpleA.getName());
- Product simpleB = SimpleFactory.createProduct("B");
- System.out.println(simpleB.getName());
-
- // 工厂方法测试代码
- Product pa = new NonCreateProductA().getObject();
- System.out.println(pa.getName());
-
- Product pb = new NonCreateProductB().getObject();
- System.out.println(pb.getName());
- }
-
- }
- // java api
- // 静态工厂方法
- Calendar.getInstance()
- java.text.NumberFormat.getInstance()
- java.util.ResourceBundle.getBundle()
-
- // 工厂方法
- java.net.URLStreamHandlerFactory
- javax.xml.bind.JAXBContext.createMarshaller