菜鸟教程之工厂模式
如下:SteveCode之工厂模式
类图:
上代码:
ChinaPizza
/**
* 功能描述:中国披萨
*
* @author Songxianyang
* @date 2022-01-17 22:26
*/
public class ChinaPizza extends Pizza{
public ChinaPizza() {
name = "中国披萨";
size = 12;
}
@Override
void box() {
System.out.println("非常之精致的盒子");
}
}
NyChina
/**
* 功能描述:牛约披萨
*
* @author Songxianyang
* @date 2022-01-17 22:27
*/
public class NyChina extends Pizza {
public NyChina() {
name = "牛约披萨";
size = 8;
}
@Override
void cut() {
System.out.println("切6片");
}
}
Pizza
/**
* 功能描述:披萨类
*
* @author Songxianyang
* @date 2022-01-17 22:18
*/
public class Pizza {
public String name;
public Integer size;
/**
* 盒子
*/
void box() {
System.out.println("普通包装盒子");
}
void cut() {
System.out.println("默认切8片");
}
public String getName() {
return this.name;
}
}
PizzaAbstract
/**
* 功能描述:披萨抽象类
*
* @author Songxianyang
* @date 2022-01-17 22:13
*/
public abstract class PizzaAbstract {
public Pizza createPizza(String type) {
Pizza pizza = typePizza(type);
pizza.box();
pizza.cut();
return pizza;
}
/**
* 获取披萨具体种类
* @param type
* @return Pizza
*/
abstract Pizza typePizza(String type);
}
TypePizzaFactory
/**
* 功能描述:披萨类型工厂
*
* @author Songxianyang
* @date 2022-01-17 22:25
*/
public class TypePizzaFactory extends PizzaAbstract{
@Override
Pizza typePizza(String type) {
if ("china".equals(type)) {
return new ChinaPizza();
}
if ("ny".equals(type)) {
return new NyChina();
}
//不友好测试用
return null;
}
}
测试类:Test
/**
* 功能描述:
*
* @author Songxianyang
* @date 2022-01-17 22:34
*/
public class Test {
public static void main(String[] args) {
TypePizzaFactory typePizza = new TypePizzaFactory();
Pizza ny = typePizza.createPizza("ny");
System.out.println("披萨名称="+ny.getName());
Pizza china = typePizza.createPizza("china");
System.out.println("披萨名称="+china.getName());
}
}
效果图
工厂模式还需要优化
为年薪百万二奋斗终身!给我冲