如果您对python之工厂函数感兴趣,那么本文将是一篇不错的选择,我们将为您详在本文中,您将会了解到关于python之工厂函数的详细内容,我们还将为您解答python工厂函数有哪些的相关问题,并且为您
如果您对python之工厂函数感兴趣,那么本文将是一篇不错的选择,我们将为您详在本文中,您将会了解到关于python之工厂函数的详细内容,我们还将为您解答python工厂函数有哪些的相关问题,并且为您提供关于Angular 依赖注入学习笔记之工厂函数的用法、PostgreSQL PL / Python如何在性能方面与Python之外的Python进行比较?、Python setattr() 函数 ,Python super() 函数: Python 内置函数 Python 内置函数、python 设计模式之工厂模式 Factory Pattern (简单工厂模式,工厂方法模式,抽象工厂模式)的有价值信息。
本文目录一览:- python之工厂函数(python工厂函数有哪些)
- Angular 依赖注入学习笔记之工厂函数的用法
- PostgreSQL PL / Python如何在性能方面与Python之外的Python进行比较?
- Python setattr() 函数 ,Python super() 函数: Python 内置函数 Python 内置函数
- python 设计模式之工厂模式 Factory Pattern (简单工厂模式,工厂方法模式,抽象工厂模式)
python之工厂函数(python工厂函数有哪些)
python之工厂函数
本人也是小白一个,最近在学习python工厂函数时随便在网上搜了搜,发现许多人对工厂函数的理解存在误区,同时也是为了整理和记录自己的思路,写下本片博文。
工厂函数顾名思义就是一个能产生函数的工厂,其目的是对一个需要输入多个参数的函数分类封装,不同使用者只需要输入更少的参数或单个参数就能调用。
方法:利用python函数输出可以是函数的功能,将某些参数传入,输出一个封装好的针对专门用户的函数,更方便用户使用。
工厂函数实现方法:
例如,学校学生成绩查询系统有一个函数如下:
def gradeCheck(instituteID,clasID,studentID): #instituteID表示学院ID号,clasID表示班级ID号,studentID是学号
institute=instituteID
clas=clasID
stuedent=studentID
result=''实现成绩查询''
return result
显然,对于某系院系而言,他们并不关心其他学院的ID,所以针对某些具体学院就可以以上述函数为基础,产生一系列函数,以方便学院子系统调用。举例如下:
对于学院ID分别为9522,9523,9524的学院子系统设计查询函数如下:
#生成各院校子系统函数
def radeCheck9522(clasID,studentID):
institute=9522
return gradeCheck(institute,clasID,studentID)
def radeCheck9523(clasID,studentID):
institute=9523
return gradeCheck(institute,clasID,studentID)
def radeCheck9524(clasID,studentID):
institute=9524
return gradeCheck(institute,clasID,studentID)
#调用:
grade1=radeCheck9522("#clasIDn","studentIDn") #参数表中输入实际的班级ID和学号
grade2=radeCheck9523("clasIDn","studentIDn") #参数表中输入实际的班级ID和学号
grade3=radeCheck9524("clasIDn","studentIDn") #参数表中输入实际的班级ID和学号
看见没,犹如工厂生产产品一样,一些列函数就产生了。新产生的函数只需要输入班级ID和学号就行了。
Angular 依赖注入学习笔记之工厂函数的用法
网址:https://angular.institute/di
We can transfer any data through our apps, transform it and replace it.
我们能传递任何数据到我们的应用里,改变其形态,并且替换。
Another case: document and fetch can work in your browser correctly. But one day you need to build your app in SSR or precompile with nodejs. Global entities might be missing or be different in that environment.
document 和 fetch 能在浏览器环境下运行。但是如果在 SSR 下 build 应用,或者用 nodejs precompile,那么这些对象在新的环境下不再可用。
Dependency Injection mechanism manages dependencies in your application. For you as an Angular developer, it is a straightforward instrument. There are two operations: you can provide something into your DI tree or take something from it.
依赖注入机制管理应用的依赖。对于 Angular 开发者来说,有两种操作:
- 提供数据到依赖注入树中
- 从依赖注入树中获取数据
The magic is the order in which you provide and take your dependencies.
Angular creates a class instance when you ask for this the first time.
当我们试图在 DI 树里第一次获取实例时,Angular 负责实例化。
Providing value is normally used with InjectionToken. This object is like a key for DI mechanism.
我们也可以用依赖注入提供常量,通常借助 InjectionToken. 这个令牌类似依赖注入机制中的 key.
You say "I want to get this data with this key" and ask DI in a component "Do you have something for this key?"
我们使用 InjectionToken 作为 key,询问 Angular 依赖注入机制,“你维护的资源里,有针对这个 key 的值吗?”
看个具体的例子。
export const API_URL = new InjectionToken<string>(''The URL of API'');
在 api-url.token.ts 里,我们从 @angular/core 里导入了标准的 InjectionToken 构造器,其类型为 string,描述信息为:The URL of API.
在 app.module.ts 里,导入这个 API_URL token,然后在 module 的 NgModule 注解里,使用 useValue 提供 token key 代表的具体值:
如何使用这个 token 呢?参考下图代码:
export class AppComponent {
constructor(@Inject(API_URL) readonly apiUrl: string) {
/**
* Here we asked for something with a key API_URL.
* There is our string in DI and we get it
*/
console.log(apiUrl);
}
}
语义就是,在 app Component 里,使用 @Inject 注解,向 DI 树里查询,是否存在 key 为 API_URL 的注入值。
- We can replace token value at any level of DI tree without any changes in a component - 我们可以在 DI 树上的任意层次结构里,替换 token 的值,而不需要修改 Component
- We can mock a token value providing suitable data in tests - 在测试代码里,我们可以 mock 一个 token 值
- The component class is fully isolated and can be used without any context
Providing a factory
这是 Angular 依赖注入的高级用法之一。
You can provide some value combining and transforming data from other tokens.
我们可以在 factory 代码里编写一些业务逻辑,执行一些数据结构变换的操作。
看个例子:
定义一个函数:
import { NgModule } from "@angular/core";
import { BrowserModule } from "@angular/platform-browser";
import { FormsModule } from "@angular/forms";
import { AppComponent } from "./app.component";
import { PRESSED_KEY } from "./tokens/pressed-key";
import { Observable, fromEvent } from "rxjs";
import { map } from "rxjs/operators";
import { DOCUMENT } from "@angular/common";
/**
* It is a token value factory.
*
* The factory is called when app.component.ts asks for
* the token PRESSED_KEY the first time
*/
function pressedKeyFactory(documentRef: Document): Observable<string> {
return fromEvent(documentRef.body, "keydown").pipe(
map((event: KeyboardEvent) => event.key)
);
}
构造一个 Observable 对象,当键盘被按下时,从 KeyboardEvent 里解析出具体哪一个键被按下,然后将 key 值通过 Observable 对象返回。
这个函数被当成一个工厂函数,本身接收类型为 Document 的参数,这个参数就是其依赖。
我们通过下列的语法,将名为 PRESSED_KEY 的令牌,和该工厂函数绑定在一起。
@NgModule({
imports: [BrowserModule, FormsModule],
declarations: [AppComponent],
bootstrap: [AppComponent],
providers: [
{
provide: PRESSED_KEY,
/**
* Here you can provide any token and its value will be injected
* as a factory function argument
*/
deps: [DOCUMENT],
useFactory: pressedKeyFactory
}
]
})
该 token 的消费方式:
更多Jerry的原创文章,尽在:"汪子熙":
PostgreSQL PL / Python如何在性能方面与Python之外的Python进行比较?
我运行完全相同的Python函数,一个作为Postgresql PL / Python,另一个作为通常的Python脚本在Postgresql之外运行.
令人惊讶的是,当我使用select * from pymax7(20000);调用Postgresql PL / Python时,它平均花费65秒,而当我调用通常的Python脚本python myscript.py 20000时,它平均需要48秒.计算运行查询和脚本10次的平均值.
是否应该有这样的差异? Postgresql RDBMS(PL / Python)中的Python如何在性能方面与Python之外的Python进行比较?
我在Ubuntu 12.04 64位上运行Postgresql 9.1和Python 2.7.
Postgresql PL / Python:
CREATE FUNCTION pymax7 (b integer)
RETURNS float
AS $$
a = 0
for i in range(b):
for ii in range(b):
a = (((i+ii)%100)*149819874987)
return a
$$LANGUAGE plpythonu;
Python:
import time
import sys
def pymax7 (b):
a = 0
for i in range(b):
for ii in range(b):
a = (((i+ii)%100)*149819874987) # keeping Python busy
return a
def main():
numIterations = int(sys.argv[1])
start = time.time()
print pymax7(numIterations)
end = time.time()
print "Time elapsed in Python:"
print str((end - start)*1000) + ' ms'
if __name__ == "__main__":
main()
我确实调整了PL / Python测试用例,使用与普通Python测试用例相同的测量技术:
CREATE FUNCTION pymax7a (b integer)
RETURNS float
AS $$
import time
start = time.time()
a = 0
for i in range(b):
for ii in range(b):
a = (((i+ii)%100)*149819874987)
end = time.time()
plpy.info("Time elapsed in Python: " + str((end - start)*1000) + ' ms')
return a
$$LANGUAGE plpythonu;
这将告诉您是否涉及任何非Python开销. FWIW,对我来说,这个打印和客户端打印的psql与总时间之间的差异始终小于1毫秒.
Python setattr() 函数 ,Python super() 函数: Python 内置函数 Python 内置函数
描述
setattr 函数对应函数 getatt(),用于设置属性值,该属性必须存在。
语法
setattr 语法:
setattr(object, name, value)
参数
- object -- 对象。
- name -- 字符串,对象属性。
- value -- 属性值。
返回值
无。
实例
以下实例展示了 setattr 的使用方法:
描述
super() 函数是用于调用父类(超类)的一个方法。
super 是用来解决多重继承问题的,直接用类名调用父类方法在使用单继承的时候没问题,但是如果使用多继承,会涉及到查找顺序(MRO)、重复调用(钻石继承)等种种问题。
MRO 就是类的方法解析顺序表, 其实也就是继承父类方法时的顺序表。
语法
以下是 super() 方法的语法:
super(type[, object-or-type])
参数
- type -- 类。
- object-or-type -- 类,一般是 self
Python3.x 和 Python2.x 的一个区别是: Python 3 可以使用直接使用 super().xxx 代替 super(Class, self).xxx :
Python3.x 实例:
class A:
pass class B(A): def add(self, x): super().add(x)
Python2.x 实例:
class A(object): # Python2.x 记得继承 object pass class B(A): def add(self, x): super(B, self).add(x)
返回值
无。
实例
以下展示了使用 super 函数的实例:
执行结果:
Parent
Child
HelloWorld from Parent Child bar fuction I''m the parent.
python 设计模式之工厂模式 Factory Pattern (简单工厂模式,工厂方法模式,抽象工厂模式)
十一回了趟老家,十一前工作一大堆忙成了狗,十一回来后又积累了一大堆又 忙成了狗,今天刚好抽了一点空开始写工厂方法模式
我看了《Head First 设计模式》P109--P133 这 25 页,讲述了我们为什么要用工厂模式,里面用做 pizza 的例子讲的特别细腻。看完了就能很清楚的知道为什么要用工厂模式。
年龄越大越不喜欢一知半解,深刻的了解某些未知的事或物以后,它再出现就不怕了
#''New'' 有什么不对劲?
在技术上,new 没有错,这是语言的基础部分。真正的犯人是我们的老朋友 ‘改变’, 以及它是如何影响 new 使用的。
如果代码是通过接口而写,通过多态,可以与任何新类实现该接口。
但是当代码使用大量的具体类时,那就麻烦了,因为一旦加入新的具体类,就必须改变代码。意思是代码没 "对修改关闭"。想用新的具体类来扩展代码,必须重新打开它。
这可咋办? 只能改代码
很明显,如果实例化某些具体类,将使 orderPizza () 出问题,没办法让 orderPizza () 对修改关闭,
但是咱们还是能很明显的看出哪些会变,哪些不会变,这个时候就可以考虑封装了,
上面这些引出了下面的简单工厂模式
#简单工厂模式
1) 算是定义吧
简单工厂模式其实并不是一个模设计模式,反而比较像一种编程习惯,还请不要把这个习惯认为是 “工厂模式”。
不要因为简单工厂不是一个真正的模式,就忽略它的用法。
2) 类图
3) 举个例子(java)
public class PizzaStore {
SimplePizzaFactory factory;
public PizzaStore(SimplePizzaFactory factory){
this.factory=factory;
}
public Pizza orderPizza(String type){
Pizza pizza;
pizza=factory.createPizza(type);
pizza.prepare();
pizza.bake();
pizza.cut();
pizza.box();
return pizza;
}
}
############################
public class SimplePizzaFactory {
public Pizza createPizza(String type){
Pizza pizza=null;
if(type.equals("cheese")){
pizza=new CheesePizza();
}else if (type.equals("greek")){
pizza=new GreekPizza();
}else if(type.equals("pepperoni")){
pizza=new PepperoniPizza();
}else if (type.equals("clam")){
pizza=new ClamPizza();
}else if (type.equals("veggie")){
pizza=new VeggiePizza();
}
return pizza;
}
}
########################################################
public abstract class Pizza {
String name;
String dough;
String sauce;
void prepare(){
System.out.print("Preparing");
};
void bake(){
System.out.print("Baking");
};
void cut(){
System.out.print("cut");
};
void box(){
System.out.print("box");
};
}
public class VeggiePizza extends Pizza{
}
public class ClamPizza extends Pizza {
}
public class PepperoniPizza extends Pizza {
}
public class PepperoniPizza extends Pizza {
}
#################################
public static void main(String[] args) {
PizzaStore store=new PizzaStore();
Pizza pizza=store.orderPizza("cheese");
System.out.println("eat Pizza");
}
4) 举个例子(python)
#工厂方法模式
#引入
# 匹萨生意火爆,现在有很多人要开加盟店,不同地区的加盟店口味有差异。PizzaStore 有个不错的订单系统,希望所有加盟店对订单的处理一致。
各区域匹萨店之间的差异在于他们制作匹萨的风味(比如 NYStyle 饼薄, ChicagoStyle 饼厚等),我们现在让 createPizza () 来应对这些变化负责创建正确种类的匹萨。
做法是让 PizzaStore 的各个子类负责定义自己的 createPizza () 方法。所以我们会得到 PizzaStore 的具体类。
#定义
定义了一个创建对象的接口,但有子类决定要实例化的类是哪一个。工厂方法让类把实例化推迟到子类。
所有工厂模式都是用来封装对象的创建。工厂方法模式 (Factory Method Pattern) 通过让子类决定该创建的对象是什么,来达到对象创建的过程封装的目的。
原本是由一个对象负责所有具体的实例化,现在变成一群子类负责实例化
# 类图
#举个例子 (java)
public abstract class PizzaStore {
public Pizza orderPizza(String type){
Pizza pizza;
pizza=createPizza(type);
pizza.prepare();
pizza.bake();
pizza.cut();
pizza.box();
return pizza;
}
abstract Pizza createPizza(String type);
}
###########################################################
public class NYPizzaStore extends PizzaStore{
Pizza createPizza(String item){
if(item.equals("cheese")){
return new NYStyleCheesePizza();
}else if (item.equals("greek")){
return new NYStyleGreekPizza();
}else if(item.equals("pepperoni")){
return new NYStylePepperoniPizza();
}else if (item.equals("clam")){
return new NYStyleClamPizza();
}else if (item.equals("veggie")){
return new NYStyleVeggiePizza();
}else return null
}
########
public class ChicagoPizzaStore extends PizzaStore {
Pizza createPizza(String item){
if(item.equals("cheese")){
return new ChicagoStyleCheesePizza();
}else if (item.equals("greek")){
return new ChicagoStyleGreekPizza();
}else if(item.equals("pepperoni")){
return new ChicagoStylePepperoniPizza();
}else if (item.equals("clam")){
return new ChicagoStyleClamPizza();
}else if (item.equals("veggie")){
return new ChicagoStyleVeggiePizza();
}else return null;
}
}
##########################################################
public abstract class Pizza {
String name;
String dough;
String sauce;
void prepare(){
}
void bake(){
}
void cut(){
}
void box(){
}
}
##############
public class NYStyleCheesePizza extends Pizza {
public NYStyleCheesePizza(){
name="NY Style Sauce and Cheese Pizza";
dough="Thin Crust Dough";
sauce="Marinara Sauce";
}
}
########
public class NYStyleClamPizza extends Pizza {
}
######
public class NYStyleGreekPizza extends Pizza{
}
####
public class NYStylePepperoniPizza extends Pizza {
}
#######
public class NYStyleVeggiePizza extends Pizza {
}
#########
public class ChicagoStyleCheesePizza extends Pizza {
public ChicagoStyleCheesePizza(){
name="Chicago Style Sauce and Cheese Pizza";
dough="Thick Crust Dough";
sauce="Plum Tomato Sauce";
}
}
#########
public class ChicagoStyleGreekPizza extends Pizza{
}
########
public class ChicagoStylePepperoniPizza extends Pizza {
}
#######
public class ChicagoStyleClamPizza extends Pizza{
}
######
public class ChicagoStyleVeggiePizza extends Pizza {
}
#####################################################################
public class javatest1 {
public static void main(String[] args) throws IOException,ClassNotFoundException{
PizzaStore nyStore=new NYPizzaStore();
PizzaStore chicagoStore=new ChicagoPizzaStore();
Pizza pizza=nyStore.orderPizza("cheese");
System.out.println("eat NYStylePizza");
pizza = chicagoStore.orderPizza("cheese");
System.out.println("eat ChicagoStylePizza");
}
}
#举个例子 (python)
class Person(object):
def __init__(self,name):
self.name = name
def work(self):
print(self.name+"工作开始了")
axe = Stone_Factory().create_axe()
axe.cut_tree()
class Axe(object):
def __init__(self,name):
self.name = name
def cut_tree(self):
print("使用%s斧头砍树"%self.name)
class StoneAxe(Axe):
def cut_tree(self):
print("使用石斧头砍树")
class SteelAxe(Axe):
def cut_tree(self):
print("使用铁斧头砍树")
class Tree(object):
pass
#工厂类
''''''
class Factory(object):
@staticmethod
def create_axe(type):
if type == "stone":
return StoneAxe("花岗岩斧头")
if type == "steel":
return SteelAxe("铁斧头")
''''''
class Factory(object):
def create_axe(self):
pass
class Stone_Factory(Factory):
def create_axe(self):
return StoneAxe("花岗岩斧头")
class Steel_Factory(Factory):
def create_axe(self):
return SteelAxe("铁斧头")
code 来自 https://blog.csdn.net/Mr_Quiet/article/details/80998337
#抽象工厂模式
# 引入
纽约匹萨店生意火爆,越来越好,需要开好多家纽约披萨店,芝加哥也是面临同样的情况。为了保证质量,就得控制原料。所以我们得建造原料工厂,来生产不同区域的原料。
#定义
抽象工厂模式提供一个接口,用于创建相关或依赖对象的家族,而不需要明确指定具体类。
允许客户用抽象的借口创建一组产品,不需要知道实际产出的具体产品是什么,这样客户就从具体的产品解耦了。
#结构图
# 使用场景
)客户端不依赖于产品类实例如何被创建、实现等细节
)强调一系列相关的产品对象(属于统一产品族)一起使用创建对象需要大量重复的代码
)提供一个产品类的库,所以的产品以同样或者大部分相同的接口出现,从而使客户端不依赖具体实现
#优点
实现解耦
# 缺点
)规定了所有可能被创建的产品集合,产品族扩展新的产品困难,需要修改抽象工厂的接口
)增加了系统的抽象性和理解难度
#举个例子 (java)
public interface Cheese {
}
#############
public interface Pepperoni {
}
##########
public interface Sauce {
}
##################
public interface Clams {
}
public class BlackOlives implements Veggies {
}
#########
public interface Dough {
}
##########
public interface Veggies {
}
######################################################################
public class MozzarellaCheese implements Cheese{
}
########
public class ReggianoCheese implements Cheese {
}
#####
public class Eggplant implements Veggies {
}
#####
public class Garlic implements Veggies{
}
#######
public class Mushroom implements Veggies {
}
###########
public class RedPepper implements Veggies{
}
########
public class Spinach implements Veggies{
}
#####
public class FreshClams implements Clams{
}
######
public class FrozenClams implements Clams{
}
#######
public class MarinaraSauce implements Sauce {
}
#########
public class PlumTomatoSauce implements Sauce {
}
########
public class SlicedPepperoni implements Pepperoni{
}
#########
public class SlicePepperoni implements Pepperoni{
}
########
public class ThinCrustDough implements Dough {
}
########
public class ThickCrustDough implements Dough {
}
########################################################
public interface PizzaIngredientFactory {
public Sauce createSauce();
public Cheese createCheese();
public Veggies[] createVeggies();
public Pepperoni createPepperoni();
public Clams createClam();
public Dough createDough();
}
###################
public class NYPizzaIngredientFactory implements PizzaIngredientFactory {
public Dough createDough(){
return new ThinCrustDough();
}
public Sauce createSauce(){
return new MarinaraSauce();
}
public Cheese createCheese(){
return new ReggianoCheese();
}
public Veggies[] createVeggies(){
Veggies veggies[]={new Garlic(),new Mushroom(),new RedPepper()};
return veggies;
}
public Pepperoni createPepperoni(){
return new SlicePepperoni();
}
public Clams createClam(){
return new FreshClams();
}
}
#########
public class ChicagoPizzaIngredientFactory implements PizzaIngredientFactory {
public Dough createDough(){
return new ThickCrustDough();
}
public Sauce createSauce(){
return new PlumTomatoSauce();
}
public Cheese createCheese(){
return new MozzarellaCheese();
}
public Veggies[] createVeggies(){
Veggies veggies[]={new BlackOlives(),new Spinach(),new Eggplant()};
return veggies;
}
public Pepperoni createPepperoni(){
return new SlicedPepperoni();
}
public Clams createClam(){
return new FrozenClams();
}
}
#######
###############################################
public abstract class Pizza {
String name;
Dough dough;
Sauce sauce;
Veggies veggies[];
Cheese cheese;
Pepperoni pepperoni;
Clams clam;
abstract void prepare();
void bake(){
System.out.print("Baking");
};
void cut(){
System.out.print("cut");
};
void box(){
System.out.print("box");
};
void setName(String name){
this.name=name;
}
String getName(){
return name;
}
public String toString(){
return name;
}
}
###############
public class CheesePizza extends Pizza{
PizzaIngredientFactory ingreditentFactory;
public CheesePizza(PizzaIngredientFactory ingredientFactory){
this.ingreditentFactory=ingredientFactory;
}
void prepare(){
System.out.print("Preparing"+name);
dough=ingreditentFactory.createDough();
sauce=ingreditentFactory.createSauce();
cheese=ingreditentFactory.createCheese();
}
}
#############
public class ClamPizza extends Pizza {
PizzaIngredientFactory ingredientFactory;
public ClamPizza(PizzaIngredientFactory ingredientFactory){
this.ingredientFactory=ingredientFactory;
}
void prepare(){
System.out.print("Preparing"+name);
dough=ingredientFactory.createDough();
sauce=ingredientFactory.createSauce();
clam=ingredientFactory.createClam();
}
}
######################
public class PepperoniPizza extends Pizza {
PizzaIngredientFactory ingreditentFactory;
public PepperoniPizza(PizzaIngredientFactory ingredientFactory){
this.ingreditentFactory=ingredientFactory;
}
void prepare(){
System.out.print("Preparing"+name);
dough=ingreditentFactory.createDough();
sauce=ingreditentFactory.createSauce();
cheese=ingreditentFactory.createCheese();
}
}
################
public class VeggiePizza extends Pizza {
PizzaIngredientFactory ingreditentFactory;
public VeggiePizza(PizzaIngredientFactory ingredientFactory){
this.ingreditentFactory=ingredientFactory;
}
void prepare(){
System.out.print("Preparing"+name);
dough=ingreditentFactory.createDough();
sauce=ingreditentFactory.createSauce();
cheese=ingreditentFactory.createCheese();
}
}
###############################################################################################
public abstract class PizzaStore {
public Pizza orderPizza(String type){
Pizza pizza;
pizza=createPizza(type);
pizza.prepare();
pizza.bake();
pizza.cut();
pizza.box();
return pizza;
}
abstract Pizza createPizza(String type);
}
############################
public class NYPizzaStore extends PizzaStore{
protected Pizza createPizza(String item){
Pizza pizza=null;
PizzaIngredientFactory nyIngredientFactory=new NYPizzaIngredientFactory();
if(item.equals("cheese")){
pizza=new CheesePizza(nyIngredientFactory);
pizza.setName("New York Style Cheese Pizza");
}else if(item.equals("veggie")){
pizza=new VeggiePizza(nyIngredientFactory);
pizza.setName("New York Style Veggie Pizza");
}else if(item.equals("clam")){
pizza=new ClamPizza(nyIngredientFactory);
pizza.setName("New York Style Clam Pizza");
}else if(item.equals("pepperoni")){
pizza=new PepperoniPizza(nyIngredientFactory);
pizza.setName("New York Style Pepperoni Pizza");
}
return pizza;
}
}
###################
public class ChicagoPizzaStore extends PizzaStore{
protected Pizza createPizza(String item){
Pizza pizza=null;
PizzaIngredientFactory nyIngredientFactory=new ChicagoPizzaIngredientFactory();
if(item.equals("cheese")){
pizza=new CheesePizza(nyIngredientFactory);
pizza.setName("New York Style Cheese Pizza");
}else if(item.equals("veggie")){
pizza=new VeggiePizza(nyIngredientFactory);
pizza.setName("New York Style Veggie Pizza");
}else if(item.equals("clam")){
pizza=new ClamPizza(nyIngredientFactory);
pizza.setName("New York Style Clam Pizza");
}else if(item.equals("pepperoni")){
pizza=new PepperoniPizza(nyIngredientFactory);
pizza.setName("New York Style Pepperoni Pizza");
}
return pizza;
}
}
###########################################################################
public class javatest1 {
public static void main(String[] args) throws IOException,ClassNotFoundException{
PizzaStore nyPizzaStore=new NYPizzaStore();
nyPizzaStore.orderPizza("cheese");
System.out.print("\n");
PizzaStore chicagoPizzaStore=new ChicagoPizzaStore();
chicagoPizzaStore.orderPizza("clam");
}
}
# 举个例子 (python)
#!/usr/bin/env python
# -*- coding:utf-8 -*-
__author__ = ''Andy''
"""
大话设计模式
设计模式——抽象工厂模式
抽象工厂模式(Abstract Factory Pattern):提供一个创建一系列相关或相互依赖对象的接口,而无需指定它们的类
"""
import sys
#抽象用户表类
class User(object):
def get_user(self):
pass
def insert_user(self):
pass
#抽象部门表类
class Department(object):
def get_department(self):
pass
def insert_department(self):
pass
#操作具体User数据库类-Mysql
class MysqlUser(User):
def get_user(self):
print ''MysqlUser get User''
def insert_user(self):
print ''MysqlUser insert User''
#操作具体Department数据库类-Mysql
class MysqlDepartment(Department):
def get_department(self):
print ''MysqlDepartment get department''
def insert_department(self):
print ''MysqlDepartment insert department''
#操作具体User数据库-Orcal
class OrcaleUser(User):
def get_user(self):
print ''OrcalUser get User''
def insert_user(self):
print ''OrcalUser insert User''
#操作具体Department数据库类-Orcal
class OrcaleDepartment(Department):
def get_department(self):
print ''OrcalDepartment get department''
def insert_department(self):
print ''OrcalDepartment insert department''
#抽象工厂类
class AbstractFactory(object):
def create_user(self):
pass
def create_department(self):
pass
class MysqlFactory(AbstractFactory):
def create_user(self):
return MysqlUser()
def create_department(self):
return MysqlDepartment()
class OrcaleFactory(AbstractFactory):
def create_user(self):
return OrcalUser()
def create_department(self):
return OrcalDepartment()
if __name__ == "__main__":
db = sys.argv[1]
myfactory = ''''
if db == ''Mysql'':
myfactory = MysqlFactory()
elif db == ''Orcal'':
myfactory = OrcaleFactory()
else:
print "不支持的数据库类型"
exit(0)
user = myfactory.create_user()
department = myfactory.create_department()
user.insert_user()
user.get_user()
department.insert_department()
department.get_department()
代码来自 https://www.cnblogs.com/onepiece-andy/p/python-abstract-factory-pattern.html
#工厂方法模式与抽象工厂模式对比
)都是负责创建对象,工厂方法模式 用的方法是通过继承,抽象工厂模式 用的方法是对象的组合
)工厂方法模式 通过子类来创建对象,客户只需要知道所使用的抽象类型,右子类来负责决定具体类型。换句话说 工厂方法模式只负责将客户从具体类型中解耦。
)抽象工厂模式 用来创建一个产品家族的抽象类型,也可以把客户从所使用的具体产品中解耦。可以把一组相关的产品集合起来。
如果需要扩展这组相关产品,就必须改变接口,这是抽象工厂的缺点。工厂方法模式只涉及一个产品。
)抽象工厂模式经常使用工厂方法模式来实现它(抽象工厂模式)的具体工厂,纯粹是用来创建产品。
参考
《Head First 设计模式》
https://blog.csdn.net/qq_28859325/article/details/60580578
https://www.jianshu.com/p/610a26d9d958
今天关于python之工厂函数和python工厂函数有哪些的介绍到此结束,谢谢您的阅读,有关Angular 依赖注入学习笔记之工厂函数的用法、PostgreSQL PL / Python如何在性能方面与Python之外的Python进行比较?、Python setattr() 函数 ,Python super() 函数: Python 内置函数 Python 内置函数、python 设计模式之工厂模式 Factory Pattern (简单工厂模式,工厂方法模式,抽象工厂模式)等更多相关知识的信息可以在本站进行查询。
本文标签: