Java设计模式--简单工厂模式
Posted 小LUA
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java设计模式--简单工厂模式相关的知识,希望对你有一定的参考价值。
简单工厂模式,又称为静态方法工厂模式。结构图如下:
实现:
水果接口:
package com.design.simplefactory; public interface Fruit { String fruitName(); }
实现类:
package com.design.simplefactory; public class Apple implements Fruit { @Override public String fruitName() { return "Big Apple"; } }
package com.design.simplefactory; public class Banana implements Fruit { @Override public String fruitName() { return "Big Banana"; } }
工厂:
package com.design.simplefactory; public class FruitFactory { public static Fruit createFriut(String name){ switch (name){ case "apple": return new Apple(); case "banana": return new Banana(); default: return null; } } public static void main(String[] args){ Fruit apple = FruitFactory.createFriut("apple"); Fruit banana = FruitFactory.createFriut("banana"); Fruit other = FruitFactory.createFriut("other"); System.out.println(apple == null?"null":apple.fruitName()); System.out.println(banana == null?"null":banana.fruitName()); System.out.println(other == null?"null":other.fruitName()); } }
输出:
以上是关于Java设计模式--简单工厂模式的主要内容,如果未能解决你的问题,请参考以下文章