下面分享的是自己学习面向对象的时候练习的案例,不过加入了工厂的思想,可能有些同学会觉得别扭,不好理解,可是这样可以解耦合,就是在阅读上和后期维护上很好用,每一个类做自己该做的事,来一起敲吧!
先看一下运行效果:
看完运行效果就来一起跟着步骤来吧~
第一步:创建一个父类披萨类:
//父类:Pizza类
public class Pizza {
private String name;
private int size;
private double price;
public Pizza() {
}
public Pizza(String name, int size, double price) {
this.name = name;
this.size = size;
this.price = price;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getSize() {
return size;
}
public void setSize(int size) {
this.size = size;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public String show(){
return "披萨名称:" + name + "\n披萨大小:"+ size +"寸\n披萨价格:" + price+"元\n";
}
}
第二步:创建子类培根披萨类继承父类披萨类
//子类,培根披萨类
public class BaconPizza extends Pizza{
private double g;
@Override
public String show() {
return super.show()+"披萨重量:"+g+"克";
}
public BaconPizza() {
}
public BaconPizza(String name, int size, double price, double g) {
super(name, size, price);
this.g = g;
}
public double getG() {
return g;
}
public void setG(double g) {
this.g = g;
}
}
第三步:创建子类水果披萨类继承父类披萨类
//子类水果披萨类
public class FruitsPizza extends Pizza{
private String Material;
@Override
public String show() {
return super.show() + "披萨材料:" + Material;
}
public FruitsPizza() {
}
public FruitsPizza(String name, int size, double price, String material) {
super(name, size, price);
Material = material;
}
public String getMaterial() {
return Material;
}
public void setMaterial(String material) {
Material = material;
}
}
第四步:创建披萨工厂类,所有的披萨在这里面生成,这个思想刚开始可能不好理解,一定不要怕,去认真的敲几十遍,在你敲10遍,20遍的时候甚至30遍,你会有不一样的感受。先学会这些思想,在把这些思想变成自己的思想。慢慢培养起来
import java.util.Scanner;
//披萨工厂类
public class PizzaFactory {
public static Pizza getPizza(int choice){
Scanner sc = new Scanner(System.in);
Pizza p = null;
switch (choice){
case 1:{
System.out.println("请输入购买尺寸:");
int size = sc.nextInt();
System.out.println("请输入购买价格:");
double price = sc.nextDouble();
System.out.println("请输入培根的克数:");
double g = sc.nextDouble();
BaconPizza B1 = new BaconPizza("培根披萨",size,price,g);
p = B1;
}
break;
case 2:{
System.out.println("请输入加入的材料:");
String material = sc.next();
System.out.println("请输入购买尺寸:");
int size = sc.nextInt();
System.out.println("请输入购买价格:");
double price = sc.nextDouble();
FruitsPizza F1 = new FruitsPizza("水果披萨",size,price,material);
p = F1;
}
break;
default:
System.out.println("输入有误,已退出......");
}
return p;
}
}
第五步:编写测试类
import java.util.Scanner;
//披萨测试类
public class Test {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("请选择要买的披萨种类:(1.培根披萨 || 2.水果披萨)");
int choice = sc.nextInt();
Pizza pizza = PizzaFactory.getPizza(choice);
System.out.println(pizza.show());
}
}
我的另一篇是没有这个披萨工厂类的,一共四个类,可以发现那个案例在测试类很多的代码,非常的臃肿,不过现在这个把做披萨提出来变成了工厂,在测试类就只是测试,在维护的时候哪一部分出了问题就专门找哪一部分,这样大大提高了阅读性,和可维护性,美观性,在以后的很多都是为了解耦合,慢慢跟着敲吧,把这个项目敲几十遍,肯定有所收获!!!