*一下仅个人学习之后的个人总结,有不足之处,欢迎留言讨论
优缺点:
1、简单工厂模式通过这种做法实现了对责任的分割,它提供了专门的工厂类用于创建对象。
2、客户端无须知道所创建的具体产品类的类名,只需要知道具体产品类所对应的参数即可,对于一些复杂的类名,通过简单工厂模式可以减少使用者的记忆量。
3、通过引入配置文件,可以在不修改任何客户端代码的情况下更换和增加新的具体产品类,在一定程度上提高了系统的灵活性。
4、由于工厂类集中了所有产品创建逻辑,一旦不能正常工作,整个系统都要受到影响。
5、使用简单工厂模式将会增加系统中类的个数,在一定程序上增加了系统的复杂度和理解难度。
6、系统扩展困难,一旦添加新产品就不得不修改工厂逻辑,在产品类型较多时,有可能造成工厂逻辑过于复杂,不利于系统的扩展和维护。
代码简单实现:
AbstrComputer类
public abstract class AbstrComputer {
public static String name;
private void shutup(){
System.out.println("电脑开机");
}
private void shutdown(){
System.out.println("电脑关机");
}
private void useComputer(){
System.out.println("使用电脑");
}
abstract void methods();
}
AbstrPhone类
public abstract class AbstrPhone {
public static String name;
private void shutup(){
System.out.println("手机开机");
}
private void shutdown(){
System.out.println("手机关机");
}
private void usePhone(){
System.out.println("使用手机");
}
abstract void methods();
}
Client(客户)
public class Client {
public static void main(String[] args) {
HuaWeiComputer computer = new ImplProductFactory().getHuaWeiComputer("新华为电脑");
computer.methods();
}
}
AbstrComputer 类
public class HuaWeiComputer extends AbstrComputer {
public HuaWeiComputer (String name){
HuaWeiComputer.name=name;
}
@Override
void methods() {
System.out.println("华为电脑特有功能");
}
}
AbstrPhone 类
public class HuaWeiPhone extends AbstrPhone {
public HuaWeiPhone(String name){
HuaWeiPhone.name=name;
}
@Override
void methods() {
System.out.println("华为手机特有功能");
}
}
ImplProductFactory 类
public class ImplProductFactory implements ProductFactory{
@Override
public MiPhone getMiPhone(String type) {
return new MiPhone(type);
}
@Override
public MiComputer getMiComputer(String type) {
return new MiComputer(type);
}
@Override
public HuaWeiPhone getHuaWeiPhone(String type) {
return new HuaWeiPhone(type);
}
@Override
public HuaWeiComputer getHuaWeiComputer(String type) {
return new HuaWeiComputer(type);
}
}
MiComputer 类
public class MiComputer extends AbstrComputer {
public MiComputer(String name){
MiComputer.name=name;
}
@Override
void methods() {
System.out.println("小米电脑特有功能");
}
}
MiPhone 类
public class MiPhone extends AbstrPhone {
public MiPhone(String name){
MiPhone.name=name;
}
@Override
void methods() {
System.out.println("小米特有功能");
}
}
ProductFactory 接口
public interface ProductFactory {
MiPhone getMiPhone(String type);
MiComputer getMiComputer(String type);
HuaWeiPhone getHuaWeiPhone(String type);
HuaWeiComputer getHuaWeiComputer(String type);
}