不确定我的标题是否正确,因为我什至不确定我使用的是正确的术语。
我有一个类,它的属性是一个对象。设置此属性时,必须创建对象。我的问题是如何在没有紧耦合的情况下做到这一点?
例子:
class A
{
protected $_depending;
protected $_somePropertyObject;
public function __construct(\Lib\Dependency $depending)
{
$this->_setDepending($depending);
}
protected function _setDepending(\Lib\Dependency $depending)
{
$this->_depending = $depending;
}
public function setSomeProperty($someProperty)
{
// I want to prevent this
$this->_somePropertyObject = new \Lib\some\Object($someProperty);
}
}
Run Code Online (Sandbox Code Playgroud)
我可以只通过构造传递所需的对象,但是还需要发生什么?
如果我正确理解了工厂模式,这会发生什么变化?我仍然需要在某处创建对象吗?不是对象本身,而是工厂。又是紧耦合?对我来说似乎无穷无尽。然而,当重构类时,它是孤立的,类是在哪里以及如何制作的。
如果我将 setSomeProperty 函数设置为只接受 \Lib\some\Object 那么它仍然需要由传递它的父对象创建。似乎只是改变了它创建的位置?
希望我对我要问的问题足够清楚。
提前致谢!
编辑我要问的是创建时间、地点、原因的顺序。
我在 C++ 中有一个旧的工厂实现,我想在其中使用唯一指针而不是原始指针。我的代码的一个最小示例如下。我有一个基类A和一个派生类B。在中main(),我传递1给中的create方法A,而b1现在的类型更改为B.
#include <iostream>
#include <map>
class A {
public:
A() {}
virtual void Foo() {}
std::map<int, A *> ®isterType() {
static std::map<int, A *> map_instance;
return map_instance;
}
A *create(int n) { return registerType()[n]; }
};
class B : A {
public:
B() { registerType()[1] = this; }
void Foo() { std::cout << "I am B!\n"; }
};
static B b0;
int …Run Code Online (Sandbox Code Playgroud) 我正在用web api编写我的第一个有角度的应用程序,我在调用工厂函数方面遇到了一些问题.
我有两个看起来像这样的工厂:
main.factory('Table', function ($http, $log) {
return {
build: function (token, cubeid) {
return $http({
method: 'POST',
url: 'http://localhost:50051/api/structure/cube',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
transformRequest: function (obj) {
var str = [];
for (var p in obj)
str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
return str.join("&");
},
data: { token: token, cubeId: cubeid }
});
}
};
});
main.factory('Login', function ($http, $log) {
return {
authorize: function (username, password) {
return $http({
method: 'POST',
url: 'path/to/api/',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' …Run Code Online (Sandbox Code Playgroud) 领域驱动设计建议我们应该通过使用工厂来创建聚合根来隐藏复杂性。我们可以通过以下方式来创建聚合根:
我们在(1)和(2)之间做出选择的依据是什么?
典型的工厂设计模式需要基类声明虚拟析构函数,但这实际上可以使用shared_ptr.
#include <iostream>
#include <memory>
#include <cstdio>
using namespace std;
class Dog {
public:
~Dog() { cout << "dog destroyed\n"; }
};
class Yellowdog : public Dog {
public:
~Yellowdog() { cout << "Yellow dog destroyed.\n"; }
};
class DogFactory {
public:
static shared_ptr<Dog> createYellowdog() {
return shared_ptr<Yellowdog>(new Yellowdog());
}
};
int main(int argc, char *argv[]) {
auto ptr = DogFactory::createYellowdog();
cout << ptr.use_count() << endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
在这种情况下,输出yellowdog destroyed后跟dog destroyed. 但为什么?为什么 using …
我试图在Typescript中实现标准的抽象工厂模式,但编译器不合作.这是我的代码的简化版本:
abstract class Model { }
class User extends Model { }
abstract class ModelFactory<T extends typeof Model> {
constructor(private modelConstructor: T) {}
public create(): T {
return new (this.modelConstructor)(); // ERROR HERE
}
}
class UserFactory extends ModelFactory<typeof User> {
constructor() {
super(User);
}
}
let user: User;
user = new UserFactory().create();
Run Code Online (Sandbox Code Playgroud)
但是,当我使用tsc 2.1编译时,我在上面指定的行中收到以下错误:
model.ts(8,13): error TS2511: Cannot create an instance of the abstract class 'Model'.
Run Code Online (Sandbox Code Playgroud)
如果我删除类型安全并将该行转换为:
return new (this.modelConstructor as any)();
Run Code Online (Sandbox Code Playgroud)
编译时没有错误.然而,这是不幸的.有没有办法在不使用演员表的情况下使这段代码可编辑?如果没有,为什么不呢?
我正在尝试使用MySQL实现数据库连接上的工厂模式,SQL Server面临奇怪的错误
你调用的对象是空的
在SQL命令对象上
internal class SqlServerDB : IDatabase
{
private SqlConnection _Connection = null;
private SqlCommand _Command = null;
public IDbCommand Command
{
get
{
if (_Command == null)
{
_Command.Connection = (SqlConnection)Connection;
//_Command = new SqlCommand();
}
return _Command;
}
}
public IDbConnection Connection
{
get
{
if (_Connection == null)
{
string connectionString = ConfigurationManager.ConnectionStrings["testSQL"].ConnectionString;
_Connection = new SqlConnection(connectionString);
}
return _Connection;
}
}
}
Run Code Online (Sandbox Code Playgroud)
数据库工厂部分:
public static class DatabaseFactory
{
public static IDatabase CreateDatabase(DBType type)
{ …Run Code Online (Sandbox Code Playgroud) 我正在尝试在数据库帮助程序类中实现单例模式,但是,我似乎无法理解工厂构造函数的用途以及是否有使用它的替代方法。
class DbHelper {
final String tblName ='';
final String clmnName ='';
final String clmnPass='';
DbHelper._constr();
static final DbHelper _db = new DbHelper._constr();
factory DbHelper(){ return _db;}
Database _mydb;
Future<Database> get mydb async{
initDb() {
if(_mydb != null)
{
return _mydb;
}
_mydb = await initDb();
return _mydb;
}
Run Code Online (Sandbox Code Playgroud) 我目前正在用 TypeScript 编写一个类工厂,并希望返回一个类型作为函数的输出。尽管 TypeScript 将类型作为输入处理——即泛型——很漂亮,但我还没有找到一种将类型作为输出处理的方法。
这个关于类工厂的 StackOverflow 问题提供了一个特别有用的解决方案,但没有完全回答我的问题。鉴于以下结构,
function factory(someVar: any) {
return class A {
// Do something with someVar that makes this class unique
}
}
Run Code Online (Sandbox Code Playgroud)
该问题表明,应该使用此工厂函数的输出执行以下操作:
import factory from "someLocation";
const AClass = factory({foo: "bar"});
type A = InstanceType<typeof AClass>;
interface IData {
someField: A;
}
Run Code Online (Sandbox Code Playgroud)
我有兴趣在我的工厂函数中包含此功能,以使系统更具可重用性或模块化。但是,正如最初所述,我不确定如何从函数返回类型。如果我尝试以下操作,TypeScript 会抛出错误[ts] 'MenuState' only refers to a type, but is being used as a value here. [2693]:
function factory(someVar: any) {
class AClass {
// Do something with …Run Code Online (Sandbox Code Playgroud) 我在 Laravel 5.7 中有以下工厂,在调用它时没有返回任何内容:
<?php
use Faker\Generator as Faker;
use Illuminate\Database\Eloquent\Model;
$factory->define(App\Record::class, function (Faker $faker) {
return [
"name" => $faker->name,
];
});
Run Code Online (Sandbox Code Playgroud)
而我的模型是:
<?php
namespace App;
use App\Product;
use Illuminate\Database\Eloquent\Model;
class Record extends Model
{
protected $table = "records";
protected $fillable = ["name"];
function __construct()
{
parent::__construct();
}
}
Run Code Online (Sandbox Code Playgroud)
我在这里调用工厂:
<?php
namespace Tests\Feature;
use Tests\TestCase;
use Illuminate\Foundation\Testing\WithoutMiddleware;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use Illuminate\Foundation\Testing\RefreshDatabase;
use App;
use App\Product;
use App\Record;
use App\User;
class RecordTest extends TestCase
{
use RefreshDatabase;
use …Run Code Online (Sandbox Code Playgroud) factory ×10
c++ ×2
javascript ×2
php ×2
typescript ×2
aggregate ×1
angularjs ×1
c# ×1
constructor ×1
dart ×1
laravel ×1
mysql ×1
object ×1
phpunit ×1
polymorphism ×1
singleton ×1
sql-server ×1
this ×1
typeerror ×1
types ×1
unique-ptr ×1