单例 网络

单例模式 就是把多次实例化的结果指向同一个实例,实例化传的值得是相同

今天单例模式总共讲了四个实现方式:

方式一:

import settings
class MySQL:
__instance=None
def __init__(self, ip, port):
self.ip = ip
self.port = port

@classmethod
def from_conf(cls):
if cls.__instance is None:
cls.__instance=cls(settings.IP, settings.PORT)
return cls.__instance
obj1=MySQL.from_conf()
obj2=MySQL.from_conf()
print(obj1)
print(obj2)


方式二:

import settings

def singleton(cls):
_instance=cls(settings.IP,settings.PORT)
def wrapper(*args,**kwargs):
if len(args) !=0 or len(kwargs) !=0:
obj=cls(*args,**kwargs)
return obj
return _instance
return wrapper

@singleton #MySQL=singleton(MySQL) #MySQL=wrapper
class MySQL:
def __init__(self, ip, port):
self.ip = ip
self.port = port


obj1=MySQL()
obj2=MySQL()
print(obj1)
print(obj2)



方式三:
import settings

class Mymeta(type):
def __init__(self,class_name,class_bases,class_dic):
#self=MySQL这个类
self.__instance=self(settings.IP,settings.PORT)

def __call__(self, *args, **kwargs):
# self=MySQL这个类
if len(args) != 0 or len(kwargs) != 0:
obj=self.__new__(self)
self.__init__(obj,*args, **kwargs)
return obj
else:
return self.__instance

class MySQL(metaclass=Mymeta): #MySQL=Mymeta(...)
def __init__(self, ip, port):
self.ip = ip
self.port = port


obj1=MySQL()
obj2=MySQL()
print(obj1)
print(obj2)


方式四:
def f1():
from singleton import instance
print(instance)

def f2():
from singleton import instance,My
SQL
print(instance)
obj=MySQL('1.1.1.3',3302)
print(obj)

f1()
f2()

settings:
  IP='1.1.1.1'
  PORT=3306

singLeton:
import settings

class MySQL:
print('run....')
def __init__(self, ip, port):
self.ip = ip
self.port = port

instance=MySQL(settings.IP,settings.PORT)


网络编程:
  C/S: Client--------基于网络----------Server 软件 客户端等
  B/S: Browser-------基于网络----------Server 页面

服务端需要遵循的原则:

  1.服务端与客户端都需要有卫衣的地址,但是服务端的地址编写固定/绑定

  2.对外一直提供服务,稳定运行
  3.服务端应该支持并发

互联网协议:

  OSI七层协议

ip+mac  可以标识全世界范围内第一无二的一台计算机的位置

port  可以标识一台计算机上唯一的一个基于网络通信的应用软件

ip+mac+port  可以标识全世界范围内独一无二的一个基于网络通信的一个应用软件

原文地址:https://www.cnblogs.com/layerluo/p/9550603.html