我有两节课.SpeciesReader获取文件并解析它们.Species存储有关物种的某些数据,这些数据已从文件中解析.
目前,我有一个方法:SpeciesReader.generateSpecies(),它使用实例化它的文件来创建一个Species对象.这是不好的做法/设计吗?我应该以某种方式找到一种方法将其移动到构造函数中Species,将文件名作为参数?
javascript中令人讨厌的问题是忘记调用new一个意图实例化的函数,导致this被绑定到一个不同的对象(通常是全局的)而不是一个新对象.我读到的一个解决方法是使用以下习语在函数构造函数中显式检查它:
function SomeConstructor(x, y, ...) {
// check if `this` is created with new
if ( !(this instanceof arguments.callee) )
return new SomeConstructor(x, y, ...);
// normal initialization code follows
Run Code Online (Sandbox Code Playgroud)
现在new SomeConstructor(...)和SomeConstructor(...)等同.
我想通过创建一个包装函数来简化这一过程,该函数factory(fn)执行前两行,然后委托给包装函数fn.这将用作:
SomeConstructor = factory(function (x, y, ...) {
// normal initialization code follows
})
Run Code Online (Sandbox Code Playgroud)
我的第一次尝试是:
function factory(fn) {
return function() {
if ( !(this instanceof arguments.callee) ) {
return new arguments.callee.apply(this, arguments);
}
fn.apply(this, arguments);
} …Run Code Online (Sandbox Code Playgroud) 我有以下代码:
class EntityBase (object) :
__entity__ = None
def __init__ (self) :
pass
def entity (name) :
class Entity (EntityBase) :
__entity__ = name
def __init__ (self) :
pass
return Entity
class Smth (entity ("SMTH")) :
def __init__ (self, a, b) :
self.a = a
self.b = b
# added after few comments -->
def factory (tag) :
for entity in EntityBase.__subclasses__ () :
if entity.__entity__ == tag :
return entity.__subclasses__ ()[0]
raise FactoryError (tag, "Unknown entity")
s = factory …Run Code Online (Sandbox Code Playgroud) 函数应该包含类的名称并返回该类型的对象.如何在C++中做到这一点?
我正在阅读Joshua Bloch写的Effective Java一书.在第一章中,他说使用工厂而不是构造函数,并列出了这种方法的优缺点.据我所知,缺点与对象构造没有密切关系.
此外,Bloch说Java Bean的构造方式也有缺点.资料来源:http://www.javapractices.com/topic/TopicAction.do? Id= 84
好的,所以使用构造函数不是很好,Java bean不是很好,工厂很好,所以你可以做一些缓存查找并避免创建额外的对象(取决于情况,有时你不想要缓存).
如果我试图避免构造函数和java bean,我应该如何创建一个对象?
我错过了一点吗?什么是最佳做法?
编辑:
class Foo{
private Foo(){}
public Foo Create(){
return new Foo();
}
}
Run Code Online (Sandbox Code Playgroud) 哪种方式使用Factory更好(正确)?
IPacket info = PacketFactory.CreatePacketObject(PacketType.Info, currentUser, DateTime.Now, " disconnected");
Run Code Online (Sandbox Code Playgroud)
或者我应该丢弃PacketFactory中的第二个方法并使用这个方法吗?
IPacket info = PacketFactory.CreatePacketObject(PacketType.Info);
info.CreationTime = DateTime.Now;
info.Creator = currentUser;
info.Data = " disconnected";
Run Code Online (Sandbox Code Playgroud)
或者其他一些?
PacketFactory代码:
public static class PacketFactory
{
public static IPacket CreatePacketObject(PacketType type)
{
IPacket packetToCreate = null;
switch (type)
{
case PacketType.Info:
packetToCreate = new Info();
break;
case PacketType.Log:
packetToCreate = new Log();
break;
case PacketType.Message:
packetToCreate = new Message();
break;
}
return packetToCreate;
}
public static IPacket CreatePacketObject(PacketType type, Client creator, DateTime creationTime, string data) …Run Code Online (Sandbox Code Playgroud) 考虑我有以下课程:
/// File classes.d
class C {
string type() { return "C"; };
}
class C1 : C {
override string type() { return "C1"; };
}
class C2 : C {
override string type() { return "C1"; };
}
Run Code Online (Sandbox Code Playgroud)
现在我想在其他地方实施工厂,例如:
/// File factory.d
module factory;
import std.functional;
import std.stdio;
void main() {
mixin(import("classes.d"));
auto c = cast(typeof(mixin("C1"))) Object.factory("C1");
writeln(c.type());
}
Run Code Online (Sandbox Code Playgroud)
编译器(dmd 2.058)说:
factory.d(7): Error argument C1 to typeof is not an expression
Run Code Online (Sandbox Code Playgroud)
我知道以下行汇编得很好:
auto c = cast(C1) Object.factory("classes.C1");
Run Code Online (Sandbox Code Playgroud)
但这需要我在编译时知道类型(C1).我想在运行时获取类型(如字符串).
我想替换这段代码:
Kernel.Bind<ITaskFactory<AlertTask>>().ToFactory();
Kernel.Bind<ITaskFactory<PopupTask>>().ToFactory();
Run Code Online (Sandbox Code Playgroud)
用这样的东西:
Kernel.Bind(scanner => scanner.FromThisAssembly().SelectAllClasses()
.EndingWith("Task").MAGICGOESHERE().BindToFactory()
Run Code Online (Sandbox Code Playgroud)
我试图创建一个IBindingGenerator,但在尝试从T获取ITaskFactory <T>时陷入困境.
从员工维护视图保存数据后,我尝试重定向到员工详细信息视图.我想在控制器的成功方法中做到这一点:
$scope.insertEmployee = function (employee) {
if (employee && $scope.IsNew) {
employeeFactory.insertEmployee(employee)
.success(function (data) {
// after a successful save, redirect the user to the details view
$location.path('/employee-details/' + employee.EmployeeNumber);
if (!$scope.$$phase)
$scope.$apply()
})
.error(function (error) {
$scope.status = 'Unable to save the employee data: ' + error;
});
}
else {
$scope.status = 'You are missing required information!';
}
};
Run Code Online (Sandbox Code Playgroud)
这是我的工厂:
factory.insertEmployee = function (employee) {
url = baseAddress + "employee/insert/";
return $http.post(url, employee);
};
Run Code Online (Sandbox Code Playgroud)
我的asp.net webapi控制器:
[Route("api/employee/insert/")]
public …Run Code Online (Sandbox Code Playgroud) Zend Framework 2中的Delegator Factories是一个强大的工具,可以用于创建标准ZF对象,并通过自定义ZF对象进行更改甚至完全复制.
我想为Hydrator创建一个Delegator Factory,以便为它附加一些Hydrator策略.但它还没有工作......
module.config.php
return array(
...
'service_manager' => array(
...
'invokables' => array(
...
'AuthenticationAdapterDelegatorFactory' => 'Foo\\MvcAuth\\Factory\\AuthenticationAdapterDelegatorFactory', // <-- it works
'DoctrineObjectHydratorDelegatorFactory' => 'Bar\\Model\\Entity\\Hydrator\\DoctrineObjectHydratorDelegatorFactory', // <-- it doesn't
),
'delegators' => array(
'ZF\\MvcAuth\\Authentication\\DefaultAuthenticationListener' => array( // <-- it works
0 => 'AuthenticationAdapterDelegatorFactory',
),
'DoctrineModule\\Stdlib\\Hydrator\\DoctrineObject' => array( // <-- it doesn't
0 => 'DoctrineObjectHydratorDelegatorFactory'
)
),
),
...
);
Run Code Online (Sandbox Code Playgroud)
由于水合物实际上是由HydratorPluginManager它提供的,我也是这样尝试的:
return array(
'service_manager' => array(
...
'invokables' => array(
...
'DoctrineObjectHydratorDelegatorFactory' => 'Bar\\Model\\Entity\\Hydrator\\DoctrineObjectHydratorDelegatorFactory', …Run Code Online (Sandbox Code Playgroud)