Володимир Семенякін “demiurg. Приручення заліза”
TRANSCRIPT
Знакомимся
- Год objective-C++ CMK
- Год C++ 4A Games
- Полгода Java SE + EE в Bionic University
- 10 статей, косящих под науку
- Около 15 опубликованных рассказов
- В планах – учиться на режиссёра
О чём пойдёт речь
Романтические бредни
Кульбиты идей без кумиров
Сёрфинг на гребняхабстракции
++11С
ШАБЛОНЫ против
ВИРТУАЛЬНОСТИ
fАнтинаучные размышления
SIM-АРХИТЕКТУРА
Алгоритмы оптимизации*
Динамические библиотеки
Гуманитарное мышление
Умные указатели
DEMIURG
Алгоритмы оптимизации*
Многослойность Модульность
Плагины Низкий уровень
Открытие ООП
Глава первая
Что это такое?
Пример
Структура
Объяснение
Истории
Краткое описание шаблона
Расширенное описание на примере
UML с указанием назначения классов
Краткое пояснение взаимодействия классов на UML
Всякие странные задачки по мотивам
IGorynych
Cards
NIICHAVO
Манифест самоделкиных
Не бойся тюрьмы, Не бойся сумы,
Не бойся ни мора, ни глада,
А бойся единственно только того,
Кто скажет: «Я знаю, как надо!»
Маленький физический этюд
Глава вторая
История удивительных превращений
MovingForce
PushingForce
GravityForce
JumpingForce
g
T
S
I
M
SIM-подход
Shell
Model Influence
ShellAbstraction
ModelPos: (100; 80)Speed: (0; 0)Rotation: 0Mass: 4.5
. . .
Influence Flex: 0.05 Obj_1: obj1 Obj_2: obj2
Physical Object
Shell
Base Property Packabstract
PrDynamic
PrOptic
PrElectricity
Model
Physical object
Shell
Base Ruleabstract
RuleOhme
RuleFerma
Influence
RuleNewton
PhysicSyst – main class of the engine
PhysicSyst – main class of the engine
O
S
I
M
Следующий шаг…
Physical Object
Shell
Model
+ =
Physical World
+
Models List
Property Packs
Rules&
Utilities
O
S
I
M
O
S
I
M
Prototypes
Программирование по Платону
или
Эпическая битва тараканов в голове
Глава третья
Какие-то мысли
Главная задача архитектуры:
Правильное распределение областей ответственности
Программа как модель Вселенной:
Точное отображение предметной области
Data Context Interaction
LINQ
Глава четвёртая
Просто написать игру
Game
UserCode
Платформонезависимая игра
Game
IGame
UserCode
Вот… Платформонезависимая
WindowsGame
AndroidGame
IGame
UserCode
Spring?!!
Game
UserCode
Хочу такое же!!.
WindowsGame
AndroidGame
IGame
UserCode
User configuration
Default сonfiguration
… с зависимостями чтобы
WindowsGame
AndroidGame
IGame
UserCode
User configuration
Default сonfiguration
С библиотечными модулями!!
Physic
.so / .dll
.aWindowsGame
AndroidGame
IGame
UserCode
User configuration
Default сonfiguration
.a
A la Maven!!!!
Physic
.so / .dll
.aWindowsGame
AndroidGame
IGame
UserCode
User configuration
Default сonfiguration
.a
С магазином библиотек!!!!!
$$$
Physic
.so / .dll
.aWindowsGame
AndroidGame
IGame
UserCode
User configuration
Default сonfiguration
.a
$$$
Physic
.so / .dll
.aWindowsGame
AndroidGame
IGame
UserCode
User configuration
Default сonfiguration
.a
Да ещё и на «плюсах»
С++
Принципы
Упрощение конфигурированияУпрощение конфигурирования
- Простота добавления зависимостей
- Простота переключения между источниками
- Простота контроля версий
Соблюдение «хороших» принциповСоблюдение «хороших» принципов
- Использование контекстной композиции
- Избегание глобальных и статических переменных
- Прозрачность жизненного цикла объектов
Window *theWindow = new Window(. . .);
View *theView0 = new View(. . .);View *theView1 = new View(. . .);
theWindow->contentView()->addSubview(theView0);theView0->addSubview(theView1);
Использование контекстной композиции
Window *theWindow = new Window(. . .);
View *theView0 = new View(. . .);View *theView1 = new View(. . .);
theWindow->contentView()->addSubview(theView0);theView0->addSubview(theView1);
Использование контекстной композиции
Window *theWindow = new Window(. . .);
View *theView0 = new View(. . .);View *theView1 = new View(. . .);
theWindow->contentView()->addSubview(theView0);theView0->addSubview(theView1);
Window *theWindow = new Window(. . .);
View *theView0 = theWindow->contentView()-> createSubview(. . .);
View *theView1 = theView0->createSubview(. . .);
Использование контекстной композиции
Window *theWindow = new Window(. . .);
View *theView0 = new View(. . .);View *theView1 = new View(. . .);
theWindow->contentView()->addSubview(theView0);theView0->addSubview(theView1);
Window *theWindow = new Window(. . .);
View *theView0 = theWindow->contentView()-> createSubview(. . .);
View *theView1 = theView0->createSubview(. . .);
Использование контекстной композиции
Window *theWindow = new Window(. . .);
View *theView0 = new View(. . .);View *theView1 = new View(. . .);
theWindow->contentView()->addSubview(theView0);theView0->addSubview(theView1);
Window *theWindow = new Window(. . .);
View *theView0 = theWindow->contentView()-> createSubview(. . .);
View *theView1 = theView0->createSubview(. . .);
Использование контекстной композиции
Window *theWindow = new Window(. . .);
View *theView0 = theWindow->contentView()-> createSubview(. . .);
View *theView1 = theView0->createSubview(. . .);
Прозрачность использования ресурсов
delete theView0;delete theView1;delete theWindow;
Window *theWindow = UIContext()->createWindow(. . .);
View *theView0 = theWindow->contentView()-> createSubview(. . .);
View *theView1 = theView0->createSubview(. . .);
Прозрачность использования ресурсов
delete theView0;delete theView1;delete theWindow;
delete theView1;delete theView0;delete theWindow;
Window *theWindow = UIContext()->createWindow(. . .);
View *theView0 = theWindow->contentView()-> createSubview(. . .);
View *theView1 = theView0->createSubview(. . .);
Прозрачность использования ресурсов
delete theView0;delete theView1;delete theWindow;
delete theView1;delete theView0;delete theWindow;
delete theWindow;
Window *theWindow = UIContext()->createWindow(. . .);
View *theView0 = theWindow->contentView()-> createSubview(. . .);
View *theView1 = theView0->createSubview(. . .);
Прозрачность использования ресурсов
delete theView0;delete theView1;delete theWindow;
delete theView1;delete theView0;delete theWindow;
delete theWindow;
Window *theWindow = UIContext()->createWindow(. . .);
View *theView0 = theWindow->contentView()-> createSubview(. . .);
View *theView1 = theView0->createSubview(. . .);
Прозрачность использования ресурсов
. . .
SomeType *theSomeVariable = new SomeType();
delete theSomeVariable;
Прозрачность использования ресурсов
SomeType *theSomeVariable = new SomeType();
delete theSomeVariable;
Прозрачность использования ресурсов
SomeType *theSomeVariable = new SomeType();
Прозрачность использования ресурсов
Я создаю объект.Объект существует, пока он мне нужен.Когда объект мне не нужен, я удаляю его.
{ }
{ MyObject theObject;
}
Объект создан
Объект удалён
copemancopeman
~ MyObject()
{ MyObject theObject;
}
Объект создан
Объект удалён
Class Struct Method Function nothing
. . .
copemancopeman
{ SmartReference theRef = new SomeType();
. . .} ~ SmartReference () { delete ptr; }
SmartReference(SomeType *p) { ptr = p; }
Умные указатели
void someFunction(SmartReference &inRef) {
SmartReference theOtherRef = inRef;
}
{ SmartReference theRef = new SomeType(); someFunction(theRef);
} ~ SmartReference () { delete ptr; }
SmartReference(SomeType *p) { ptr = p; }
SmartReference(SmartReference &r) { ptr = r.ptr; }
~ SmartReference () { delete ptr; }
Умные указатели
void someFunction(SmartReference &inRef) {
SmartReference theOtherRef = inRef;
}
{ SmartReference theRef = new SomeType(); someFunction(theRef);
} ~ SmartReference () { delete ptr; }
SmartReference(SomeType *p) { ptr = p; }
SmartReference(SmartReference &r) { ptr = r.ptr; }
~ SmartReference () { delete ptr; }
1
2
3
4
Умные указатели
void someFunction(SmartReference &inRef) {
SmartReference theOtherRef = inRef;
}
{ SmartReference theRef = new SomeType(); someFunction(theRef);
} ~ SmartReference () { delete ptr; }
SmartReference(SomeType *p) { ptr = p; }
SmartReference(SmartReference &r) { ptr = r.ptr; }
~ SmartReference () { delete ptr; }
1
2
3
4
Умные указатели
{ SmartReference theRef = new HolderType(SomeType());
someFunction(theRef);
} ~ SmartReference () { --h_p->own_count; if (0 == h_p->own_count) delete h_p;}
SmartReference(HolderType *h) { h_p = h; ++h_p->own_count; }
HolderType(SomeType &v) { val = v; own_count = 1; }
Умные указатели
void someFunction(SmartReference &inRef) {
SmartReference theOtherRef = inRef;
}
{ SmartReference theRef = new HolderType(SomeType()); someFunction(theRef);
}
11
121
0
Умные указатели
MemoryHoldervoid retain( ) = 0void release( ) = 0
CountedMemoryHoldervoid retain( ) { inc (r_count)}
void release( ) { dec (r_count) (r_count == 0) => remove()}
void remove( ) = 0
AllocatingCounted\MemoryHolder
void remove( ) { allocator.dealloc(this)}
Умные указатели
DStrongReference<SomeType> theStrongReference = theStorage.create();
DSomeStorage<SomeType> theStorage;
Контекст, в котором живут объекты:
Любое место программы:
DWeakReference<SomeType> theWeakReference = theStrongReference;
Любое другое место программы:
Умные указатели
Window *theWindow = new Window(. . .);
View *theView0 = new View(. . .);View *theView1 = new View(. . .);
theWindow->contentView()->addSubview(theView0);theView0->addSubview(theView1);
Window *theWindow = new Window(. . .);
View *theView0 = theWindow->contentView()-> createSubview(. . .);
View *theView1 = theView0->createSubview(. . .);
Умные указатели
Умные указатели
DHeapStorage<SomeType> theWindowsStorage;
DStrongReference<Window> theWindow = theWindowsStorage.createWindow(…);
DStrongReference<View> theView0 = theWindow->contentView()->createSubview(. . .);
DStrongReference<View> theView1 = theView0->createSubview(. . .);
Тонкая виртуальная машина
Точное отображение предметной области
void avadaKedavra(. . .);
.cpp.cpp .h
static MyLonelyClass sTexasRanger;
.h .cpp.cpp .h
.h
Контексты
.cpp
.cpp
.h
class Application {public: void avadaKedavra(. . .); MyLonelyClass &getTexasRanger( );}
.h.cpp.h
.cpp.h
Контексты
class ApplicationContext {private: DStrongReference<Window> _window; DStrongReference<View> _view0; DStrongReference<View> _view1;
public: void initialize( ) { _window = sHeapStorage()->create<Window>(…);
_view0 = _window->contentView()->createSubview(. . .); _view1 = theView0->createSubview(. . .); }}
?
Умные указатели
X
class ApplicationContext {private: DStrongReference<Window> _window; DStrongReference<View> _view0; DStrongReference<View> _view1;
public: void initialize( ) { _window = sHeapStorage()->create<Window>(…);
_view0 = _window->contentView()->createSubview(. . .); _view1 = theView0->createSubview(. . .); }}
verify()
Умные указатели
X
Контексты
- Контролёр взаимодействия объектов
Контекст – это:
- Фабрика объектов
- Интерфейс библиотеки
- Точка доступа к окружению
- «Система» в прототипном подходе
ContextManager
Context0 Context1 Context2
Контексты
ContextManager
Context0 Context1 Context2
Контексты
ContextManager
PlugIn0 PlugIn1 PlugIn2
Контексты
ContextManager
PlugIn0 LoopContext PlugIn2
Контексты
Плагины
Один раз написано. Компилируется везде
Внутренние реализации
Уровень интерфейсных связокУровень интерфейсных связок
Уровень реализацийУровень реализаций
Уровень прикладного кодаУровень прикладного кода
Упрощение связывания с реализациями
Связки
Что-то вроде Spring
DPlugInHolder Контроль жизненного циклаплагина с учётом спецификиместа его хранения
DPlugIn Реализация функционала
Решение зависимостей междуплагинами
Инъекция зависимостей
Минимальное описаниесобственных зависимостей
DPlugInManager
Плагины
DPackagePlugInHolder
DRAMPlugInHolder
Плагины
Хранение плагина воперативной памяти
Получение плагиновиз пакета – внешнегохранилища (например,из HDD)
SPlugIn0SDeveloper’sside only!
SPlugIn1S
DPlugIn1D
DPlugIn2D
DApplicationD
BUILD
RUN TIME
Простота добавления зависимостей
class DSomePlugIn : public DPlugIn{public:
// Plug-in public methodsD_EXPORT void foo() D_SUFFIX;
. . .
// Inherited plug-in implementationstatic void fillDescriptor(DPlugInDescriptor &);virtual void initialMediumRequest(DPlugInMediator &);virtual void initialize();
};
Простота добавления зависимостей
static void fillDescriptor(DPlugInDescriptor &);
virtual void initialize();
virtual void initialMediumRequest(DPlugInMediator &);
outMediator.addBinding("DVirtualDeviceRAM", _dependencies.virtualDeviceRAM);
outDescriptor.setName("DWindowBasedGUIContext“);
outDescriptor.addDependecy("DVirtualDeviceRAM“, [“MTag"]);
// Some initializing after dependency injection
Простота добавления зависимостей
outDescriptor.setTag(“Platform::Windows”);
static void fillDescriptor(DPlugInDescriptor &);
virtual void initialize();
outMediator.addBinding("DVirtualDeviceRAM", _dependencies.virtualDeviceRAM);
outDescriptor.setName("DWindowBasedGUIContext“);
outDescriptor.addDependecy("DVirtualDeviceRAM“, [“MTag"]);
// Some initializing after dependency injection
Простота добавления зависимостей
outDescriptor.setTag(“Platform::Windows”);
Inteface
UserCode
NS_0::Tag_Outer::Tag_InnerNS_1::Tag. . .
NS::ExtraTag
D_EXPORT void foo() D_SUFFIX;
Простота переключения между источниками
D_EXPORT void foo() D_SUFFIX;
virtual -
DynamicInterface
DynamicImplementation
Static“Interface”
StaticImplementation
virtual = 0;
- -
- -
Простота переключения между источниками
.h.dll / .so
some_dynamic_package
implementation (.dll) / (.so)
interface
some_dynamic_package
some_dynamic_package.h
...
Пакетные библиотеки
.h.а
some_static_package
some_static_package (.a)
interface
some_static_package
some_static_package.h
...
Пакетные библиотеки
dynamic
packages
interface
implementation (.dll / .so)
dynamic_package_0
…
dynamic_package_1…
…
static
static_package_0 (.a)
static_package_1 (.a)
static_package_0
interface…
…
static_package_1…
#include <some_package_0/ interface/package.h>
Library search path:-L "..\..\packages_shared\static“
Static library flag:-l static_package_0
Just runtime binding
Demiurg SDK
DPlugIn
DSystemLoopManager
DWindowBasedUIContext
DVirtualDevice
DHDDVirtualDevice
DGPUVirtualDevice
DLoopManager
DLoopContext
DDemiurgCore
DExampleApplicationContext Examples
DRAMVirtualDevice
Проблемы
_view1->addSubview(_view0);
package.a ???
Ресурсные пакеты
???
??????
??????
_window = 0; ??????
Install
1. Скачать demiurg_sdk
2. Установить и связать с проектом
3. Описать зависимости плагина
Цель: моментальный старт
4. Собрать и запустить приложение
// Inherited plug-in implementationstatic void fillDescriptor(DPlugInDescriptor &);virtual void initialMediumRequest(DPlugInMediator &);virtual void initialize();
Download
Build
Суть: Магазин программных библиотекЦелевая аудитория: Разработчики
Цель: Магазин
Суть: Магазин приложенийЦелевая аудитория: Обычные пользователи
Цель: Магазин